- 1 year ago
C# wait for thread to finish without blocking UI
To wait for a thread to finish without blocking the UI in C#, you can use the Task
and async/await
keywords to perform asynchronous operations. Here's an example of how you can achieve this:
csharpusing System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
// Start a task asynchronously
Task task = Task.Run(DoLongRunningOperation);
// Perform other UI-related tasks while waiting for the thread to finish
// For example, update UI elements or handle user input
// Wait for the task to complete without blocking the UI thread
await task;
// Thread has finished executing at this point
MessageBox.Show("Thread finished!");
}
private void DoLongRunningOperation()
{
// Simulate a long-running operation
Thread.Sleep(5000);
}
}
In this example, when the button is clicked, a long-running operation is started in a separate thread using Task.Run
. The async
keyword allows the method to be asynchronous, and the await
keyword is used to wait for the task to complete without blocking the UI thread.
While waiting for the thread to finish, the UI remains responsive, allowing you to update UI elements or handle user input. Once the task is complete, the code after the await
statement is executed.
Note that the async/await
pattern requires a compatible version of the .NET framework (4.5 or later) and is typically used with UI frameworks that support asynchronous operations, such as Windows Forms or WPF.
By using the Task
and async/await
keywords, you can wait for a thread to finish without blocking the UI, ensuring a responsive user interface while performing background operations.