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.
+2
A:
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.
Jeff Hardy
2010-06-10 17:19:55
I actually came across this and tried it, but noticed one issue... if ScriptSource.Execute() throws and exception, it doesn't get caught by the try catch block surrounding the task call. it just breaks at that line... is there any way to handle the exception on this tread?
Adam Haile
2010-06-10 19:16:37
I would move the .Execute() call to a new function and place the try/catch in that function, and then use the new function ala `Task.Factory.StartNew(MyExecute)`, or `Task.Factory.StartNew(() => MyExecute(...))` if you need the closure.
Jeff Hardy
2010-06-10 19:47:42
+2
A:
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);
}
Tom E
2010-06-10 17:30:16