如何暂停或停止"CSharpScript"跑步? [英] How to pause or stop "CSharpScript" running?
本文介绍了如何暂停或停止"CSharpScript"跑步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在应用程序中使用Roslyn的脚本API,代码片段如下:
I'm using Roslyn's scripting API in my application, code snippet as following:
public class ScriptEngine
{
public static string CodeText;
public static event Action<string[]> CompileErrorEvent;
public static async Task<bool> RunScriptAsync(CancellationToken ct)
{
try
{
var scriptResult = await CSharpScript.RunAsync(CodeText, null, new ScriptHost(), null, ct);
return true;
}
catch (Microsoft.CodeAnalysis.Scripting.CompilationErrorException ex)
{
List<string> result = new List<string>();
foreach (var item in ex.Diagnostics)
{
result.Add(item.ToString());
}
if (result.Count > 0)
{
CompileErrorEvent?.Invoke(result.ToArray());
}
return false;
}
catch (Exception ex)
{
IMCP_Base.Dialog.Show.SimpleError("脚本运行", ex.Message, "修改脚本");
return false;
}
}
.......
}
public static CancellationTokenSource ScriptCTS;
private async void btnScriptRun_ItemClick(object sender, ItemClickEventArgs e)
{
ScriptCTS = new CancellationTokenSource();
if (CheckScriptEditorIsNotNull())
{
Script.ScriptEngine.CodeText = ScriptEditor.GetCode();
bool runSuccess = await Script.ScriptEngine.RunScriptAsync(ScriptCTS.Token);
}
}
private void btnScriptStop_ItemClick(object sender, ItemClickEventArgs e)
{
ScriptCTS?.Cancel();
}
CSharpScript.RunAsync
方法运行良好,但是当我单击ScriptStop
按钮时,ScriptCTS?.Cancel()
无法取消正在运行的脚本.
CSharpScript.RunAsync
method runs well, but when I click ScriptStop
button, ScriptCTS?.Cancel()
can't cancel running script.
如何停止或暂停脚本的运行?
How can I stop or pause a script running?
推荐答案
如果您想要脚本中的取消点,则可以使用 globals ,然后传入CancelationToken
,然后您可以在脚本中签入以进行取消.
If you want cancellation points within your scripts, you can use globals, and pass in the CancelationToken
, which you can then check in your scripts for cancellation.
这篇关于如何暂停或停止"CSharpScript"跑步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文