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

Question:

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);
Asked By: ash

||

Answers:

This issue was caused by the way Python handles threads. The main thread must start the Python engine and enable threading.

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

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

Answered By: ash