user24172100
user24172100

Reputation: 21

GIL() must be released error when using PythonNet to call python scripts from C# file

I'm running a class within a larger application that uses PythonNet to call functions from within a python script. I first run these lines if the Python Engine wasn't already initialized -

Runtime.PythonDLL = @"C:\Users\micro\AppData\Local\Programs\Python\Python39\python39.dll"; 
PythonEngine.Initialize();  
Py.GIL();

and then the rest of the functionality is within this section -

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;
            }

Basically the python script returns a list that is then saved into C#. Everything in here works perfectly when run, with no errors!

The issue happens when the application runs after this class is supposedly finished executing. If I let it run for 10-15 minutes after this block is finished, I get the error

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()

The error is thrown inside the PythonNet code, so I'm not sure where the issue really is.

I've tried moving everything into another block under using (var gil = Py.GIL()){}, I've tried gil.Dispose(), I tried making a destructor for the class that included both gil.Dispose() and PythonEngine.Shutdown(), and I tried adding PythonEngine.BeginAllowThreads() in the first step above as well. I'm not sure I'm correctly understanding where the error is thrown and what exactly is causing it. Nothing I've tried so far has worked, and so I'd love some help!

Upvotes: 2

Views: 378

Answers (0)

Related Questions