IronPython内存释放问题

原始代码:

ScriptEngine eng = IronPython.Hosting.Python.CreateEngine();

优化后的代码:

复制代码
var options = new Dictionary<string, object> { ["LightweightScopes"] = true };
ScriptEngine eng = IronPython.Hosting.Python.CreateEngine(AppDomain.CurrentDomain, options);
var scope = eng.CreateScope();
using (var streamOut = new MemoryStream())
{
    ICollection<string> Paths = eng.GetSearchPaths();
    Paths.Add(Environment.CurrentDirectory + @"\Lib");
    Paths.Add(Environment.CurrentDirectory + @"\Lib\site-packages");
    eng.SetSearchPaths(Paths);
    eng.Runtime.IO.SetOutput(streamOut, Encoding.ASCII);
    var pycode="the python code you need execute";//你需要执行的python代码
    eng.Execute(pycode, scope);
    string printS = Encoding.UTF8.GetString(streamOut.ToArray());//python代码执行的print输出结果
    eng.Runtime.Shutdown();
}
复制代码

注意:

1.GC.Collect()对此处内存回收作用不大。

2.如果需要循环调用python,不建议重复CreateEngine,运行速度会变慢,可使用下面代码生成ScriptEngine:

复制代码
private ScriptEngine _eng;
public ScriptEngine eng
{
    get
    {
        if (_eng != null)
        {
            return _eng;
        }
        else
        {
            var options = new Dictionary<string, object> { ["LightweightScopes"] = true };
            _eng = Python.CreateEngine(AppDomain.CurrentDomain, options);
            return _eng;
        }
    }
    set
    {
        _eng = value;
    }
}
复制代码

3.调用eng.Runtime.Shutdown();关闭ScriptEngine的Runtime。

4.如果通过下面代码的方式获取ScriptEngine ,会造成无法获取python的输出结果(也就是上面代码的printS为空)。

ScriptEngine eng
{
    get
    {
        var options = new Dictionary<string, object> { ["LightweightScopes"] = true };
        return IronPython.Hosting.Python.CreateEngine(AppDomain.CurrentDomain, options);
    }
}
posted @   新*  阅读(73)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律

喜欢请打赏

扫描二维码打赏

支付宝打赏

点击右上角即可分享
微信分享提示