首页 >后端开发 >C++ >如何在.NET中异步等待进程退出而不阻塞?

如何在.NET中异步等待进程退出而不阻塞?

Susan Sarandon
Susan Sarandon原创
2025-01-05 11:44:39602浏览

How Can I Asynchronously Wait for Process Exit in .NET Without Blocking?

带有事件的异步 Process.WaitForExit()

询问 Process.WaitForExit() 的非阻塞替代方案导致了这一发现有价值的事件驱动方法。这种异步模式与 .NET 4.0/C# 5 及更高版本特别相关,提供了一种优雅的解决方案。

请考虑以下代码片段:

/// <summary>
/// Waits asynchronously for the process to exit.
/// </summary>
/// <param name="process">The process to wait for cancellation.</param>
/// <param name="cancellationToken">A cancellation token. If invoked, the task will return
/// immediately as canceled.</param>
/// <returns>A Task representing waiting for the process to end.</returns>
public static Task WaitForExitAsync(this Process process,
    CancellationToken cancellationToken = default(CancellationToken))
{
    if (process.HasExited) return Task.CompletedTask;

    var tcs = new TaskCompletionSource<object>();
    process.EnableRaisingEvents = true;
    process.Exited += (sender, args) => tcs.TrySetResult(null);
    if (cancellationToken != default(CancellationToken))
        cancellationToken.Register(() => tcs.SetCanceled());

    return process.HasExited ? Task.CompletedTask : tcs.Task;
}

要使用此异步方法,只需调用它如下所示:

public async void Test()
{
   var process = new Process("processName");
   process.Start();
   await process.WaitForExitAsync();

   //Do some fun stuff here...
}

通过采用这种事件驱动的异步方法,您可以有效地监控流程完成情况,而无需损害 UI 响应能力。

以上是如何在.NET中异步等待进程退出而不阻塞?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn