gpt4 book ai didi

c# - Process.WaitForExit() 异步

转载 作者:IT王子 更新时间:2023-10-29 03:56:59 28 4
gpt4 key购买 nike

我想等待一个进程完成,但是 Process.WaitForExit() 挂起了我的 GUI。是否有基于事件的方式,或者我是否需要生成一个线程来阻塞直到退出,然后自己委托(delegate)事件?

最佳答案

从 .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...
}

关于c# - Process.WaitForExit() 异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/470256/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com