开发者

Running IronPython Script in C# Asynchronously

In C# 4.0 and IronPython 2.6, is it possible to e开发者_开发问答xecute a python script in it's own thread? I would like to spawn off the script after passing in some event handler objects so that it can update the GUI as it runs.


I would use a Task:

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

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

The IronPython script will then run on a separate thread. Make sure your event handlers use the appropriate synchronization mechanism when updating the GUI.


You could use a background worker to run the script on a separate thread. Then use the ProgressChanged and RunWorkerCompleted event handlers to update the 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);
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜