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