Many applications require waiting for other processes to complete. By default, using Process.WaitForExit() causes the calling thread to block, potentially freezing the GUI. This article explores an event-based approach to achieve asynchronous process waiting in .NET.
With the enhancements introduced in .NET 4.0 and C# 5, we can elegantly represent asynchronous waiting using the async pattern. The following code snippet demonstrates how:
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 the asynchronous waiting functionality, simply invoke the WaitForExitAsync() method on a Process instance:
public async void Test() { var process = new Process("processName"); process.Start(); await process.WaitForExitAsync(); //Do some fun stuff here... }
The asynchronous approach allows your GUI to remain responsive while waiting for the process to complete. It also eliminates the need for manual thread creation and event delegation.
The above is the detailed content of How Can I Asynchronously Wait for a Process to Exit in .NET?. For more information, please follow other related articles on the PHP Chinese website!