4
让我们假设我有这样的代码进行测试。如何在单独的线程中执行IronPython脚本,然后挂起它?
public class SimpleScheduler
{
public Script Script { get; set; }
private Thread _worker;
public void Schedule()
{
this._worker = new Thread(this.Script.Execute);
this._worker.Start();
}
public void Sleep()
{
//?
}
}
SimpleScheduler
只是需要Script
对象,并试图在单独的线程来执行它。
public class Script
{
public string ID { get; set; }
private ScriptSource _scriptSource;
private ScriptScope _scope;
private CompiledCode _code;
private string source = @"import clr
clr.AddReference('Trampoline')
from Trampoline import PythonCallBack
def Start():
PythonCallBack.Sleep()";
public Script()
{
_scriptSource = IronPythonHelper.IronPythonEngine.CreateScriptSourceFromString(this.source);
_scope = IronPythonHelper.IronPythonEngine.CreateScope();
_code = _scriptSource.Compile();
}
public void Execute()
{
_code.Execute(_scope);
dynamic start = _scope.GetVariable("Start");
start();
}
}
Script
类尝试回调PythonCallBack
类的睡眠功能,并希望暂停一段时间。
public static class PythonCallBack
{
public static SimpleScheduler Scheduler;
static PythonCallBack()
{
Scheduler = new SimpleScheduler();
}
public static void Sleep()
{
Scheduler.Sleep();
}
}
PythonCallBack仅用于调用SimpleScheduler的睡眠方法。
问题: 挂起线程,执行脚本的最佳方法是什么?然后如何恢复这个线程执行?
Suspend()和Resume()方法已弃用且线程同步不安全 – 2010-10-28 08:46:25
已更新答案。 – 2010-10-28 09:23:18