Adam Haile
Adam Haile

Reputation: 31359

Running IronPython Script in C# Asynchronously

In C# 4.0 and IronPython 2.6, is it possible to execute 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.

Upvotes: 2

Views: 2829

Answers (2)

Tom E
Tom E

Reputation: 2482

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);
  }

Upvotes: 3

Jeff Hardy
Jeff Hardy

Reputation: 7662

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.

Upvotes: 3

Related Questions