.NET 7 code:
\nnamespace SimpleDotNetApi\n{\n public class SimpleDotNetApiClass\n {\n public bool DotNetDoWork()\n {\n for (int i = 0; i < 10; i++)\n {\n Console.WriteLine($\"DotNetDoWork {i}\");\n Thread.Sleep( 1000 );\n }\n return true;\n }\n }\n}Output:
\ndo_python_work 0\nDotNetDoWork 0\ndo_python_work 1\ndo_python_work 2\ndo_python_work 3\nDotNetDoWork 1\ndo_python_work 4\ndo_python_work 5\ndo_python_work 6\nDotNetDoWork 2\ndo_python_work 7\ndo_python_work 8\ndo_python_work 9\nDotNetDoWork 3\nDotNetDoWork 4\nDotNetDoWork 5\nDotNetDoWork 6\nDotNetDoWork 7\nDotNetDoWork 8\nDotNetDoWork 9\n.NET returned: True\nAm I misunderstanding something?
\nCode attached: PythonCallingDotNetThreadingTest.zip
","upvoteCount":1,"answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"In #2209 (reply in thread) @lostmsu answered this question:
\n\n","upvoteCount":1,"url":"https://github.com/pythonnet/pythonnet/discussions/2424#discussioncomment-11252913"}}}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().
\nThe wiki is outdated.
\n
-
|
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.
-
|
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: