Asynchronous Process Completion with Process.WaitForExit()
When waiting for a process to complete using Process.WaitForExit(), one may encounter a GUI freeze due to the blocking nature of the method. To overcome this issue, consider employing an event-driven approach.
In .NET 4.0 and C# 5, the async pattern provides an elegant solution to this problem. The WaitForExitAsync extension method allows you to wait asynchronously for a process to exit. Here's the code:
/// <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; }
Usage:
public async void Test() { var process = new Process("processName"); process.Start(); await process.WaitForExitAsync(); //Do some fun stuff here... }
With WaitForExitAsync, you can wait for a process to complete without blocking your GUI. It uses an event-based approach to notify the calling code when the process exits, allowing for a more responsive and interactive user experience.
The above is the detailed content of How Can I Avoid GUI Freezes When Waiting for Asynchronous Process Completion in C#?. For more information, please follow other related articles on the PHP Chinese website!