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

How Can I Asynchronously Wait for Process Exit in .NET Without Blocking?

Susan Sarandon
Susan SarandonOriginal
2025-01-05 11:44:39699browse

How Can I Asynchronously Wait for Process Exit in .NET Without Blocking?

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!

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