@@ -42,28 +42,39 @@ application.
42
42
43
43
Before interacting with any of the objects or APIs provided by the
44
44
``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() `:
55
49
56
50
.. code :: csharp
57
51
58
52
using (Py .GIL ())
59
53
{
60
54
PythonEngine .Exec (" doStuff()" );
61
55
}
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
+ }
62
73
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.
67
78
68
79
Passing C# Objects to the Python Engine
69
80
---------------------------------------
0 commit comments