使用pythonnet在C#进行多线程运行

本文介绍了如何在C#环境中利用pythonnet库解决GIL限制,实现多线程运行Python代码。具体步骤包括从github下载pythonnet源码,修改pythonengine.cs文件,然后生成dll,最后提供了引用生成dll的多线程测试代码示例。
摘要由CSDN通过智能技术生成

问题描述:NET multi-threaded execution Python method, in Py. GIL can not run
解决方案:https://github.com/pythonnet/pythonnet/issues/109

具体解决步骤,下载pythonnet-master,解压后打开pythonnet.sln,点击Python.Runtime项目目录下的pythonengine.cs,按照以上网站修改代码,在Python.Runtime项目下生成dll文件。

以下为引用pythonnet生成的dll文件的测试多线程的简单代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Python.Runtime;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Threading;

namespace MultithreadingApplication
{
    class ThreadCreationProgram
    {
        public static void CallToChildThread()
        {
            using (Py.GIL())
            {
                
                Console.WriteLine("1");
            }
            Console.WriteLine("2
很高兴回答这个问题!PythonNet库可以很方便地在C#中调用Python代码。要实现多接口不同线程调用,可以使用Python的multiprocessing库来创建多进程,每个进程可以运行一个Python接口,并且在C#中通过PythonNet库调用各个进程。这样可以实现多接口同时运行,而且不同接口之间互不干扰。以下是示例代码: ```csharp using System; using Python.Runtime; class Program { static void Main(string[] args) { // 初始化Python运行环境 PythonEngine.Initialize(); // 创建并启动多进程 dynamic multiprocessing = Py.Import("multiprocessing"); dynamic processes = new PyList(); for (int i = 0; i < 3; i++) { dynamic process = multiprocessing.Process(target: "python_interface.py"); process.Start(); processes.Append(process); } // 调用各个进程的Python接口 dynamic pythonInterface1 = Py.Import("python_interface1"); dynamic pythonInterface2 = Py.Import("python_interface2"); dynamic pythonInterface3 = Py.Import("python_interface3"); Py.GIL(); var result1 = pythonInterface1.run(); var result2 = pythonInterface2.run(); var result3 = pythonInterface3.run(); Py.GIL().Dispose(); // 输出结果 Console.WriteLine(result1); Console.WriteLine(result2); Console.WriteLine(result3); // 等待所有进程结束 foreach (dynamic process in processes) { process.Join(); } // 释放Python运行环境 PythonEngine.Shutdown(); } } ``` 希望这个示例能够帮助你实现多接口不同线程调用。如果你还有其他问题,欢迎继续提问!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值