帶有事件的非同步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中文網其他相關文章!