- Notifications
You must be signed in to change notification settings - Fork750
Calling long running C# from Python: Do I really need to call PythonEngine.BeginAllowThreads() ?#2424
-
The following pagehttps://github.com/pythonnet/pythonnet/wiki/Threading However I wrote a simple test and found that calling PythonEngine.BeginAllowThreads() is not required i.e. the Python script is not held up by the call to .NET. Python 3.12 code: frompathlibimportPathimportthreadingimporttimeimportpythonnetpythonnet.set_runtime("coreclr")importclrmy_path=Path(__file__).parentassembly_location=my_path/"SimpleDotNetApiSolution\\bin\\Debug\\net7.0\\SimpleDotNetApi"clr.AddReference(str(assembly_location))fromSimpleDotNetApiimportSimpleDotNetApiClassdefdo_python_work():foriinrange(10):print(f"do_python_work{i}")time.sleep(0.3)threading.Thread(target=do_python_work).start()simple_dotnet_api_obj=SimpleDotNetApiClass()result=simple_dotnet_api_obj.DotNetDoWork()print(".NET returned:",result) .NET 7 code: namespaceSimpleDotNetApi{publicclassSimpleDotNetApiClass{publicboolDotNetDoWork(){for(inti=0;i<10;i++){Console.WriteLine($"DotNetDoWork{i}");Thread.Sleep(1000);}returntrue;}}} Output:
Am I misunderstanding something? Code attached:PythonCallingDotNetThreadingTest.zip |
BetaWas this translation helpful?Give feedback.
All reactions
In#2209 (reply in thread)@lostmsu answered this question:
This might be confusing. I believe by default now GIL is not held when .NET code is called from Python. So actually in order to work with any Python objects you have to call and hold Py.GIL().
The wiki is outdated.
Replies: 1 comment
-
In#2209 (reply in thread)@lostmsu answered this question:
|
BetaWas this translation helpful?Give feedback.