这基本上是对 IronPython 控制台如何处理 Ctrl-C 的改编。如果要检查源,它位于BasicConsole
and中CommandLine.Run
。
首先,在单独的线程上启动 IronPython 引擎(如您所假设的)。当您运行用户的代码时,将其包装在一个try ... catch(ThreadAbortException)
块中:
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
}
现在,您需要方便地保留对 IronPython 线程的引用。在表单上创建一个按钮处理程序,然后调用Thread.Abort()
.
public void StopButton_OnClick(object sender, EventArgs e) {
pythonThread.Abort(new Microsoft.Scripting.KeyboardInterruptException(""));
}
该KeyboardInterruptException
参数允许 Python 线程捕获ThreadAbortException
并将其作为KeyboardInterrupt
.