如何通过CancellationToken停止异步进程

本文关键字:异步 进程 何通过 CancellationToken | 更新日期: 2023-09-27 18:26:21

我在代码下面找到了在不冻结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();

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

如何通过CancellationToken停止异步进程

简单的答案是,当令牌被取消时,您只需调用process.Kill()

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

但这有两个问题:

  1. 如果您试图终止一个尚不存在或已终止的进程,则会得到一个InvalidOperationException
  2. 如果您不Dispose()Register()返回的CancellationTokenRegistration,而CancellationTokenSource是长寿命的,则内存泄漏,因为注册将与CancellationTokenSource一样长时间地留在内存中

根据您的需求和对干净代码的渴望(即使以复杂性为代价),可以忽略问题#2,通过在catch中吞下异常来解决问题#1。

现在很简单:

process.WaitForExitAsync(token);