我需要一些帮助来找到我遇到的内存泄漏的解决方案.我有一个C#应用程序(.NET v3.5),允许用户运行Iron
Python脚本进行测试.脚本可以加载Python标准库中的不同模块(包含在IronPython二进制文件中).但是,当脚本完成时,分配给导入模块的内存不会被垃圾回收.循环使用一个脚本的多次运行(完成压力测试)会导致系统在长期使用期间耗尽内存.
这是我正在做的简化版本.
脚本类主要功能:
public void Run()
{
// set up iron python runtime engine
this.engine = Python.CreateEngine(pyOpts);
this.runtime = this.engine.Runtime;
this.scope = this.engine.CreateScope();
// compile from file
PythonCompilerOptions pco = (PythonCompilerOptions)this.engine.GetCompilerOptions();
pco.Module &= ~ModuleOptions.Optimized;
this.script = this.engine.CreateScriptSourceFromFile(this.path).Compile(pco);
// run script
this.script.Execute(this.scope);
// shutdown runtime (run atexit functions that exist)
this.runtime.Shutdown();
}
加载随机模块的示例’test.py’脚本(添加~1500 KB的内存):
import random
print "Random number: %i" % random.randint(1,10)
一种循环机制,会导致系统内存不足:
while(1)
{
Script s = new Script("test.py");
s.Run();
s.Dispose();
}
我根据我在this线程中找到的内容添加了部分以不优化编译,但是内存泄漏发生在任何一种方式.将显式调用添加到s.Dispose()也没有任何区别(如预期的那样).我目前正在使用IronPython 2.0,但我也尝试过升级到IronPython 2.6 RC2而没有任何成功.
当脚本引擎/运行时超出范围时,如何将嵌入式IronPython脚本中的导入模块像普通.NET对象一样进行垃圾收集?