如何通过CancellationToken停止异步处理?

时间:2015-12-10 10:36:04

标签: c# async-await cancellation

我发现在代码下执行某些进程而没有冻结UI。按下“开始工作”按钮时执行此代码。我认为用户可以通过“停止”按钮停止这项工作。所以我在MSDN上发现了这篇文章。https://msdn.microsoft.com/en-us/library/jj155759.aspx。但是,在此代码中应用此CancellationToken很难......任何人都可以帮助解决这个问题吗?

我只使用public static async Task<int> RunProcessAsync(string fileName, string args)方法。

代码(来自https://stackoverflow.com/a/31492250):

public static async Task<int> RunProcessAsync(string fileName, string args)
{
    using (var process = new Process
    {
        StartInfo =
        {
            FileName = fileName, Arguments = args,
            UseShellExecute = false, CreateNoWindow = true,
            RedirectStandardOutput = true, RedirectStandardError = true
        },
        EnableRaisingEvents = true
    })
    {
        return await RunProcessAsync(process).ConfigureAwait(false);
    }
}

// This method is used only for internal function call.
private static Task<int> RunProcessAsync(Process process)
{
    var tcs = new TaskCompletionSource<int>();

    process.Exited += (s, ea) => tcs.SetResult(process.ExitCode);
    process.OutputDataReceived += (s, ea) => Console.WriteLine(ea.Data);
    process.ErrorDataReceived += (s, ea) => Console.WriteLine("ERR: " + ea.Data);

    bool started = process.Start();
    if (!started)
    {
        //you may allow for the process to be re-used (started = false) 
        //but I'm not sure about the guarantees of the Exited event in such a case
        throw new InvalidOperationException("Could not start process: " + process);
    }

    process.BeginOutputReadLine();
    process.BeginErrorReadLine();

    return tcs.Task;
}

用法:

var cancelToken = new CancellationTokenSource();
int returnCode = async RunProcessAsync("python.exe", "foo.py", cancelToken.Token);
if (cancelToken.IsCancellationRequested) { /* something */ }

单击开始按钮时,会启动一些python脚本。 当脚本运行并且用户想要停止它时,用户按下停止按钮。 然后程序在代码下执行。

cancelToken.Cancel();

非常感谢你阅读这个问题。

2 个答案:

答案 0 :(得分:9)

简单的答案是,您可以在取消令牌时致电process.Kill()

cancellationToken.Register(() => process.Kill());

但这有两个问题:

  1. 如果您尝试终止尚未存在或已终止的流程,则会获得InvalidOperationException
  2. 如果您没有Dispose()CancellationTokenRegistration返回的Register(),并且CancellationTokenSource是长期存在的,那么您的内存会有泄漏,因为注册将会停留在内存中只要CancellationTokenSource
  3. 根据您的要求和您对清洁代码的需求(即使以复杂性为代价),可以忽略问题#2并通过吞噬catch中的异常来解决问题#1。 / p>

答案 1 :(得分:2)

现在很简单:

process.WaitForExitAsync(token);