如何暂停或停止“CSharpScript”运行?

时间:2017-01-04 13:15:36

标签: c# roslyn cs-script

我在我的应用程序中使用了Roslyn的脚本API,代码片段如下:

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()无法取消正在运行的脚本。

如何停止或暂停运行脚本?

1 个答案:

答案 0 :(得分:0)

如果您想在脚本中添加取消点,可以使用globals,然后传入CancelationToken,然后您可以在脚本中检查取消。