Windows Forms: Update Progress Bar from Async Task in C#

How to use IProgress to update a Progress Bar from Async Await Task in C# Windows Forms Application.

In asynchronous programming, when you want to handle certain Task, and want to return the percentage of Task progress to display on your Progress bar.

To update a progress bar from an asynchronous task in C#, you typically need to utilize some form of event handling or callback mechanism to report the progress of the task back to the UI thread. One common approach is to use the Progress<T> class along with async and await to report progress updates.

Here's a basic example of how you can achieve this:

How to use IProgress to update the Progress Bar in C#

To update a progress bar from an asynchronous task using IProgress<T>, you need to follow these steps.

Create a new Windows Forms Application project, then design a simple UI by dragging progress bar, button controls from your Visual Studio toolbox to your form and layout your UI as shown below.

update progress bar from async task in c#

We define a method DoSomething that simulates a long-running asynchronous task, then we pass an IProgress<int> object to DoSomething. Inside DoSomething method, we report progress by calling Report on the progress reporter object.

In ReportProgress, which is the method subscribed to the progress reporter, we update the progress bar UI.

public void DoSomething(IProgress<int> progress)
{
    for (int i = 1; i <= 100; i++)
    {
        // Simulate some work
        Thread.Sleep(100);
        if (progress != null)
            progress.Report(i);// Report progress
    }
}

Next, add code to handle the start button click event as the following code.

private async void btnStart_Click(object sender, EventArgs e)
{
    progressBar1.Value = 0;
    // Create a Progress<T> instance to report progress updates
    var progress = new Progress<int>(percent =>
    {
        // Update the progress bar value
        progressBar1.Value = percent;
    });
    / Start the asynchronous operation
    await Task.Run(() => DoSomething(progress));
}

In this example, we create a Progress<int> instance to report progress updates to the UI thread.

Inside the DoSomethingk method, we loop from 1 to 100 and report progress using the progress.Report(i) method.

When the Start button is clicked, we start the asynchronous operation using Task.Run() and await its completion.

Inside the asynchronous method, we call the DoSomething method, passing the progress reporter. As progress updates are reported, the progressBar value is updated accordingly.

Using the IProgress call back the percentage returned quickly, then update progress bar from async method. When the Start button is clicked, the progress bar value will change as the async task runs.

Remember, Report method can be called from any thread, as Progress<T> internally handles synchronization for you, ensuring safe access to the progress data.