This is basically an adaptation of how the IronPython console handles Ctrl-C. If you want to check the source, it's in BasicConsole
and CommandLine.Run
.
First, start up the IronPython engine on a separate thread (as you assumed). When you go to run the user's code, wrap it in a try ... catch(ThreadAbortException)
block:
var engine = Python.CreateEngine();
bool aborted = false;
try {
engine.Execute(/* whatever */);
} catch(ThreadAbortException tae) {
if(tae.ExceptionState is Microsoft.Scripting.KeyboardInterruptException) {
Thread.ResetAbort();
aborted = true;
} else { throw; }
}
if(aborted) {
// this is application-specific
}
Now, you'll need to keep a reference to the IronPython thread handy. Create a button handler on your form, and call Thread.Abort()
.
public void StopButton_OnClick(object sender, EventArgs e) {
pythonThread.Abort(new Microsoft.Scripting.KeyboardInterruptException(""));
}
The KeyboardInterruptException
argument allows the Python thread to trap the ThreadAbortException
and handle it as a KeyboardInterrupt
.