C# 如何在单独的线程中执行IronPython脚本,然后将其挂起?
假设我有这样的测试代码C# 如何在单独的线程中执行IronPython脚本,然后将其挂起?,c#,multithreading,thread-safety,ironpython,scheduling,C#,Multithreading,Thread Safety,Ironpython,Scheduling,假设我有这样的测试代码 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 v
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
类的Sleep函数,并希望暂停一段时间
public static class PythonCallBack
{
public static SimpleScheduler Scheduler;
static PythonCallBack()
{
Scheduler = new SimpleScheduler();
}
public static void Sleep()
{
Scheduler.Sleep();
}
}
PythonCallBack只用于调用SimpleScheduler的sleep方法
问题:
挂起执行脚本的线程的最佳方式是什么?然后如何恢复此线程执行?线程
类有一个Suspend()
和resume()
方法。这些方法挂起并恢复线程。尽管有关于此方法的警告,但这不应该是问题,因为您正在已知位置挂起
另一种方法是使用事件。您可以将脚本
或脚本范围
设置为a类自动resetEvent
。然后,在Sleep()
中,对事件调用WaitOne()
。然后,从外部,当您希望线程恢复时,调用Set()
Suspend()和resume()方法是不推荐的,对于线程同步是不安全的