Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Calling long running C# from Python: Do I really need to call PythonEngine.BeginAllowThreads() ?#2424

Discussion options

The following pagehttps://github.com/pythonnet/pythonnet/wiki/Threading
Says:

image

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:

do_python_work 0DotNetDoWork 0do_python_work 1do_python_work 2do_python_work 3DotNetDoWork 1do_python_work 4do_python_work 5do_python_work 6DotNetDoWork 2do_python_work 7do_python_work 8do_python_work 9DotNetDoWork 3DotNetDoWork 4DotNetDoWork 5DotNetDoWork 6DotNetDoWork 7DotNetDoWork 8DotNetDoWork 9.NET returned: True

Am I misunderstanding something?

Code attached:PythonCallingDotNetThreadingTest.zip

You must be logged in to vote

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

Comment options

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.

You must be logged in to vote
0 replies
Answer selected byDareDevilDenis
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Q&A
Labels
None yet
1 participant
@DareDevilDenis

[8]ページ先頭

©2009-2025 Movatter.jp