1717
1818- Reference ``Python.Runtime.dll `` (e.g. via a ``PackageReference ``)
1919- Call ``PythonEngine.Initialize() `` to initialize Python
20- - Call ``PythonEngine.ImportModule (name) `` to import a module
20+ - Call ``var mod = PyModule.Import (name) `` to import a module as `` mod ``
2121
2222The module you import can either start working with your managed app
2323environment at the time its imported, or you can explicitly lookup and
@@ -42,28 +42,39 @@ application.
4242
4343Before interacting with any of the objects or APIs provided by the
4444``Python.Runtime `` namespace, calling code must have acquired the Python
45- global interpreter lock by calling the ``PythonEngine.AcquireLock ``
46- method. The only exception to this rule is the
47- ``PythonEngine.Initialize `` method, which may be called at startup
48- without having acquired the GIL.
49-
50- When finished using Python APIs, managed code must call a corresponding
51- ``PythonEngine.ReleaseLock `` to release the GIL and allow other threads
52- to use Python.
53-
54- A ``using `` statement may be used to acquire and release the GIL:
45+ global interpreter lock by ``using'' ``Py.GIL() ``. The only exception to
46+ this rule is the ``PythonEngine.Initialize `` method, which may be called
47+ at startup without having acquired the GIL. The GIL is released again
48+ by disposing the return value of `Py.GIL() `:
5549
5650.. code :: csharp
5751
5852 using (Py .GIL ())
5953 {
6054 PythonEngine .Exec (" doStuff()" );
6155 }
56+
57+ // or
58+ {
59+ using var _ = Py .GIL ()
60+ PythonEngine .Exec (" doStuff()" );
61+ }
62+
63+ // or
64+ var gil = Py .GIL ();
65+ try
66+ {
67+ PythonEngine .Exec (" doStuff()" );
68+ }
69+ finally
70+ {
71+ gil .Dispose ();
72+ }
6273
63- The AcquireLock and ReleaseLock methods are thin wrappers over the
64- unmanaged ``PyGILState_Ensure `` and ``PyGILState_Release `` functions
65- from the Python API, and the documentation for those APIs applies to the
66- managed versions.
74+ The `` Py.GIL()'' object is a thin wrapper over the unmanaged
75+ ``PyGILState_Ensure `` (on construction) and ``PyGILState_Release `` (on
76+ disposal) functions from the Python API, and the documentation for those
77+ APIs applies to the managed versions.
6778
6879Passing C# Objects to the Python Engine
6980---------------------------------------
0 commit comments