c# – 如何在单独的线程中执行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类的Sleep函数,并希望暂停一段时间.

public static class PythonCallBack
{
    public static SimpleScheduler Scheduler;

    static PythonCallBack()
    {
        Scheduler = new SimpleScheduler();
    }

    public static void Sleep()
    {
        Scheduler.Sleep();
    }
}

PythonCallBack只是用于调用SimpleScheduler的sleep方法.

题:
暂停执行脚本的线程的最佳方法是什么?然后如何恢复此线程执行?

最佳答案 Thread类有一个Suspend()和Resume()方法.这些方法暂停并恢复线程.即使有关于此方法的警告,这也不应成为问题,因为您要暂停在已知位置.

另一种方法是使用事件.您可以为Script或ScriptScope类提供AutoResetEvent.然后,在Sleep()中,在事件上调用WaitOne().然后,从外部,当您希望线程恢复时,您调用Set().

点赞