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

This post shows you how to use IProgress to update the Progress Bar from Async/Await Task in C#.NET 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 play the demo, we will design a simple UI by dragging a progress bar and a button from your visual studio toolbox to your windows forms application, then layout your UI as shown below.

update progress bar from async task in c#

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

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProgressBarDemo
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }

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

        private async void btnStart_Click(object sender, EventArgs e)
        {
            progressBar1.Value = 0;
            var progress = new Progress<int>(percent =>
            {
                progressBar1.Value = percent;

            });
            await Task.Run(() => DoSomething(progress));
        }
    }
}

You can use IProgress to call back the percentage returned quickly, then update progress bar from async method. Click the Start button, the progress bar value will change when the async task runs.