如何处理使用(Py.GIL())块pythonnet中的异常

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

在使用 (Py.GIL()) 块时有没有办法处理异常?

例如:

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

我问这个问题是因为我调用了一个使用 using(Py.GIL()) 块的 C# 函数。它使用主线程等待完成的新线程执行。

它在第一轮工作,但在下一轮,它停止在 using block,应用程序冻结,没有显示任何异常。

我什至尝试让Main线程停止等待执行,但工作线程在第一轮后仍然停在Py.GIL()using block

对于线程执行,我使用的是线程池。

Thread.Factory.StartNew(FunctionName);

此问题是由于 Python 处理线程的方式造成的。 主线程必须初始化 Python 引擎并允许线程。

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

运行 在使用使用 using(Py.GIL()) block.

的工作线程之前,主线程上的上述代码