如何停止加载了CSScript的脚本
本文关键字:脚本 CSScript 何停止 加载 | 更新日期: 2023-09-27 17:58:01
我使用CS脚本库在WPF应用程序中运行用户定义的脚本。如果脚本无休止地运行,我如何取消它?当我的用户编写脚本时,我不能依赖脚本中检查的取消标志。
以下是显示问题的简化代码片段:
public partial class MainWindow : Window
{
public string MessageFromScript
{
get { return (string)GetValue(MessageFromScriptProperty); }
set { SetValue(MessageFromScriptProperty, value); }
}
public static readonly DependencyProperty MessageFromScriptProperty =
DependencyProperty.Register("MessageFromScript", typeof(string), typeof(MainWindow), new PropertyMetadata(null));
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
BackgroundWorker worker = null;
private void OnStart(object sender, RoutedEventArgs e)
{
if(worker != null)
{
return;
}
worker = new BackgroundWorker();
worker.DoWork += RunScript;
worker.RunWorkerCompleted += ScriptCompleted;
worker.WorkerSupportsCancellation = true;
worker.RunWorkerAsync();
}
private void ScriptCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(e.Cancelled)
MessageFromScript = "Script cancelled";
else
MessageFromScript = e.Result.ToString();
}
private void RunScript(object sender, DoWorkEventArgs e)
{
dynamic script = CSScript.Evaluator.LoadCode(@"using System;
using System.Threading;
public class Script
{
public string Test()
{
{int count=0; while(true) { count++; Console.WriteLine(count.ToString()); Thread.Sleep(200); }}
return ""Message from script"";
}
}");
e.Result = script.Test();
}
private void OnStop(object sender, RoutedEventArgs e)
{
if(worker == null)
{
return;
}
//TODO: How do I stop the script here?
worker = null;
}
}
在Test()方法中,添加一个参数,将CancellationToken传递给脚本。然后在脚本中设计循环,以检查是否已请求中止并中断。要停止脚本,只需调用CancellationTokenSource的Cancel()方法,该方法在调用时传递给脚本。