Home > Backend Development > C++ > How Can I Avoid GUI Freezes When Waiting for Asynchronous Process Completion in C#?

How Can I Avoid GUI Freezes When Waiting for Asynchronous Process Completion in C#?

DDD
Release: 2025-01-04 22:05:41
Original
803 people have browsed it

How Can I Avoid GUI Freezes When Waiting for Asynchronous Process Completion in C#?

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;
}
Copy after login

Usage:

public async void Test() 
{
   var process = new Process("processName");
   process.Start();
   await process.WaitForExitAsync();

   //Do some fun stuff here...
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template