在C#中异步运行IronPython脚本

时间:2010-06-10 12:58:45

标签: c# asynchronous ironpython c#-4.0

在C#4.0和IronPython 2.6中,是否可以在自己的线程中执行python脚本? 我希望在传入一些事件处理程序对象后生成脚本,以便它可以在运行时更新GUI。

2 个答案:

答案 0 :(得分:3)

我会使用Task

ScriptEngine engine = ...;
// initialize your script and events

Task.Factory.StartNew(() => engine.Execute(...));

然后,IronPython脚本将在一个单独的线程上运行。更新GUI时,请确保事件处理程序使用适当的同步机制。

答案 1 :(得分:3)

您可以使用后台工作程序在单独的线程上运行脚本。然后使用ProgressChanged和RunWorkerCompleted事件处理程序更新ui。

  BackgroundWorker worker;
  private void RunScriptBackground()
  {
     string path = "c:\\myscript.py";
     if (File.Exists(path))
     {            
        worker = new BackgroundWorker();
        worker.DoWork += new DoWorkEventHandler(bw_DoWork);
        worker.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
        worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        worker.RunWorkerAsync();
     }
  }

  private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  {
     // handle completion here
  }

  private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
  {
     // handle progress updates here
  }

  private void bw_DoWork(object sender, DoWorkEventArgs e)
  {
     // following assumes you have setup IPy engine and scope already
     ScriptSource source = engine.CreateScriptSourceFromFile(path);
     var result = source.Execute(scope);
  }