Calling long running C# from Python: Do I really need to call PythonEngine.BeginAllowThreads() ? #2424
-
The following page https://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: from pathlib import Path
import threading
import time
import pythonnet
pythonnet.set_runtime("coreclr")
import clr
my_path = Path(__file__).parent
assembly_location = my_path / "SimpleDotNetApiSolution\\bin\\Debug\\net7.0\\SimpleDotNetApi"
clr.AddReference(str(assembly_location))
from SimpleDotNetApi import SimpleDotNetApiClass
def do_python_work():
for i in range(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: namespace SimpleDotNetApi
{
public class SimpleDotNetApiClass
{
public bool DotNetDoWork()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine($"DotNetDoWork {i}");
Thread.Sleep( 1000 );
}
return true;
}
}
} Output:
Am I misunderstanding something? Code attached: PythonCallingDotNetThreadingTest.zip |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
In #2209 (reply in thread) @lostmsu answered this question:
|
Beta Was this translation helpful? Give feedback.
In #2209 (reply in thread) @lostmsu answered this question: