我正在一个较大的应用程序中运行一个类,该应用程序使用 PythonNet 从 python 脚本中调用函数。如果 Python 引擎尚未初始化,我首先运行这些行 -
Runtime.PythonDLL = @"C:\Users\micro\AppData\Local\Programs\Python\Python39\python39.dll";
PythonEngine.Initialize();
Py.GIL();
然后其余功能都在本节中 -
using (var scope = Py.CreateScope())
{
dynamic sys = Py.Import("sys");
sys.path.append(@"C:\Users\micro\source\repos\REFWebApp\REFWebApp.Server\Evaluation\STTs\");
var scriptCompiled = Py.Import(scriptname);
string[] message = filenames;
var result = scriptCompiled.InvokeMethod("transcribe_all", message.ToPython());
PyObject[] pylist = result.AsManagedObject(typeof(PyObject[])) as PyObject[];
List<string> transcriptions = new List<string>();
foreach (PyObject pyobject in pylist)
{
string transcript = (string)pyobject.AsManagedObject(typeof(string));
Console.WriteLine(transcript);
transcriptions.Add(transcript);
}
Console.WriteLine(transcriptions);
return transcriptions;
}
基本上,Python 脚本返回一个列表,然后将其保存到 C# 中。运行时这里的一切都完美运行,没有错误!
当应用程序在此类应该完成执行后运行时,就会出现此问题。如果我让它在这个块完成后运行 10-15 分钟,我会收到错误
System.InvalidOperationException: GIL must always be released, and it must be released from the same thread that acquired it.
at Python.Runtime.Py+GILState()+Finalize()
错误是在PythonNet代码中抛出的,所以我不确定问题到底出在哪里。
我尝试将所有内容移到
using (var gil = Py.GIL()){}
下的另一个块中,我尝试过gil.Dispose()
,我尝试为包含gil.Dispose()
和PythonEngine.Shutdown()
的类创建一个析构函数,并且我尝试在中添加PythonEngine.BeginAllowThreads()
上面的第一步也是如此。我不确定我是否正确理解错误在哪里抛出以及到底是什么原因导致的。到目前为止我尝试过的都没有成功,所以我希望得到一些帮助!
我尝试将所有内容移动到 using (var gil = Py.GIL()){}
下的另一个块中
这不可能产生同样的错误。