Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exception in using(Py.GIL()) block pythonnet

Is there a way to handle exceptions in using the (Py.GIL()) block?

For example:

   using System;
   using Python.Runtime;

   public class Test{
        public static void Main(){
           using(Py.GIL()){
               try{
                   dynamic module = Py.Import("module");
                   dynamic result = module.function("argument");

                   Console.WriteLine(result);
               }
               catch(Excepiton ex){
                   // Handled Exception
               }
           }
        }
    }

I asked this question because I call a C# function which uses the using(Py.GIL()) block. It is executed with a new thread which the Main thread waits for to finish.

It works for the first round, but for the next, it stops on the using block, and the application freezes without showing any exception.

I even tried to stop the Main thread from waiting for the execution, but the worker thread still stops at the using block of Py.GIL() after the first round.

For the thread execution, I am using the Thread pool.

Thread.Factory.StartNew(FunctionName);
like image 801
ash Avatar asked Mar 13 '17 08:03

ash


1 Answers

This problem was due to how Python handles threads. The Main thread had to initialize the Python Engine and Allow Threading.

PythonEngine.Initialize();
PythonEngine.BeginAllowThreads();

Run the above code on the Main thread before using worker thread that uses using(Py.GIL()) block.

like image 168
ash Avatar answered Nov 01 '22 11:11

ash