Asynchronous Process.WaitForExit() with Events
Inquiring about a non-blocking alternative to Process.WaitForExit() has led to the discovery of a valuable event-driven approach. Particularly relevant for .NET 4.0/C# 5 and above, this async pattern offers an elegant solution.
Consider the following code snippet:
/// <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; }
To utilize this async method, simply call it as follows:
public async void Test() { var process = new Process("processName"); process.Start(); await process.WaitForExitAsync(); //Do some fun stuff here... }
By embracing this event-driven, asynchronous approach, you can efficiently monitor process completion without compromising UI responsiveness.
The above is the detailed content of How Can I Asynchronously Wait for Process Exit in .NET Without Blocking?. For more information, please follow other related articles on the PHP Chinese website!