Home >Backend Development >C++ >How Can I Asynchronously Wait for a Process to Exit in .NET?

How Can I Asynchronously Wait for a Process to Exit in .NET?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-04 17:28:43824browse

How Can I Asynchronously Wait for a Process to Exit in .NET?

Asynchronous Process Waiting with Process.WaitForExit()

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.

Event-Based Asynchronous Waiting

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;
}

Usage

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

Benefits

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn