using CloudBuilder.Core.DatabaseAccessor.Entity; using Python.Runtime; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CloudBuilder.Topshelf.Python { public class Python39Command { private bool _disposed = false; // 释放标记 public dynamic PythonCreateScope { get; set; } public IApplicationService ApplicationService; public Python39Command(IApplicationService applicationService) { ApplicationService = applicationService; Runtime.PythonDLL = applicationService.Configuration["Python39:PythonCommand"]; PythonEngine.PythonHome = applicationService.Configuration["Python39:PythonHome"]; PythonEngine.Initialize(); PythonCreateScope = Py.CreateScope(); } public void Exec(string arg) { using (Py.GIL()) { PythonCreateScope.Exec(arg);//"from pyhanlp import HanLP" } } public string GetValueExec(string arg) { using (Py.GIL()) { PythonCreateScope.Exec(string.Format("s_value={0}", arg)); var value = PythonCreateScope.Eval("s_value"); return value.ToString(); } } public string[] GetValuesExec(string arg) { using (Py.GIL()) { PythonCreateScope.Exec(string.Format("s_list={0}", arg)); var value = PythonCreateScope.Eval("s_list"); string[] st = value.As(); return st; } } // 核心:释放 Python.NET 资源 public void Dispose() { Dispose(true); GC.SuppressFinalize(this); // 阻止析构函数重复执行 } protected virtual void Dispose(bool disposing) { if (_disposed) return; // 1. 释放 Python 作用域 if (PythonCreateScope != null) { PythonCreateScope.Dispose(); PythonCreateScope = null; } // 2. 关闭 Python 运行时(关键!) if (PythonEngine.IsInitialized) { AppContext.SetSwitch("System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization", true); PythonEngine.Shutdown(); // 销毁 Python 解释器 } _disposed = true; } } }