Environment
- Pythonnet version: 3.0.1
- Python version: 3.9.13
- Operating System: Windows 11
- .NET Runtime: .NET Core 3.1
Details
I'm trying to prevent a long running method in C# from blocking execution in Python. I followed the guidance on https://github.com/pythonnet/pythonnet/wiki/Threading but I am getting a crash.
import pythonnet
pythonnet.load('coreclr')
import os
bin_path = os.path.normpath(os.path.dirname(os.path.abspath(__file__)) + "/../LongRunningTask/bin/Debug/netcoreapp3.1")
import clr
clr.AddReference(os.path.join(bin_path, "LongRunningTask"))
clr.AddReference("System")
from LongRunningTask import LongRunningTask
from threading import Thread, Timer
t1 = Thread(target=LongRunningTask.Run)
t1.daemon = True
t1.start()
using System.Threading;
using Python.Runtime;
namespace LongRunningTask
{
public class LongRunningTask
{
public static void Run()
{
var state = PythonEngine.BeginAllowThreads();
Thread.Sleep(1000);
PythonEngine.EndAllowThreads(state);
}
}
}
- If there was a crash, please include the traceback here.
Fatal Python error: PyGILState_Release: thread state 000001D4A5CA2A40 must be current when releasing
Python runtime state: initialized
Thread 0x00001c08 (most recent call first):
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\threading.py", line 917 in run
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\threading.py", line 980 in _bootstrap_inner
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\threading.py", line 937 in _bootstrap
Current thread 0x00005f6c (most recent call first):
File "C:\Users\shersh\AppData\Roaming\Python\Python39\site-packages\clr_loader\types.py", line 64 in __call__
File "C:\Users\shersh\AppData\Roaming\Python\Python39\site-packages\pythonnet\__init__.py", line 157 in unload
Fatal error. System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at Python.Runtime.Runtime.PyGILState_Release(Python.Runtime.Native.PyGILState)
at Python.Runtime.PythonEngine.ReleaseLock(Python.Runtime.Native.PyGILState)
at Python.Runtime.Py+GILState.Dispose()
at Python.Runtime.Loader.Shutdown(IntPtr, Int32)