Home >Backend Development >C++ >How Can I Asynchronously Wait for Process Exit in C# Without Freezing the GUI?

How Can I Asynchronously Wait for Process Exit in C# Without Freezing the GUI?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-04 14:25:43430browse

How Can I Asynchronously Wait for Process Exit in C# Without Freezing the GUI?

Waiting for Process Exit Asynchronously

In many applications, it is essential to wait for a process to exit before proceeding further. However, using Process.WaitForExit() can cause the graphical user interface (GUI) to freeze. To avoid this issue, an event-based or thread-based solution is required.

Event-Based Approach

As of .NET 4.0/C# 5, the async pattern provides a more elegant way to represent the waiting process. The WaitForExitAsync() method can be added to the Process class, enabling the application to asynchronously wait for the process to exit:

public static Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default(CancellationToken))

Inside the method:

  • If the process has already exited, the method returns a completed task immediately.
  • Otherwise, a TaskCompletionSource is created and the EnableRaisingEvents property of the process is set to true.
  • An event handler is attached to the Exited event of the process, which sets the result of the task completion source when the process exits.
  • If a cancellation token is provided, it is registered to cancel the task if invoked.
  • The task is returned, which is completed when the process exits or when the cancellation token is invoked.
  • Usage

    To use the WaitForExitAsync() method:

    public async void Test()
    {
        var process = new Process("processName");
        process.Start();
        await process.WaitForExitAsync();
    
        // Do some fun stuff here...
    }

    The above is the detailed content of How Can I Asynchronously Wait for Process Exit in C# Without Freezing the GUI?. 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