How to use Progress Bar in C#

By FoxLearn 11/13/2024 9:38:16 AM   6.94K
To implement a progress bar using the Task Parallel Library in C#, you'll typically use a Progress<T> object to report progress from a background task to the UI thread.

Open your Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "ProgressBarExample" and then click OK

Winform progress bar in C#

Drag and drop the Button, Label and ProgressBar controls from the Toolbox onto the form.

You can design your form as shown below.

progress bar in c#

Set the Minimum property of the ProgressBar to 0.

Set the Maximum property to the total number of steps in your operation (for example, 100).

How to progress bar with Task Parallel in C#?

You need to create a ProgressReport class to display percent

public class ProgressReport
{
    public int PercentComplete { get; set; }
}

Add a click event handler to the button

// progress bar c# class
private Task ProcessData(List<string> list, IProgress<ProgressReport> progress)
{
    int index = 1;
    int totalProcess = list.Count;
    var progressReport = new ProgressReport();
    //Start a new thead to process data
    return Task.Run(() => {
        for (int i = 0; i < totalProcess; i++)
        {
            progressReport.PercentComplete = index++ * 100 / totalProcess;
            progress.Report(progressReport);
            Thread.Sleep(10);//used to simulate length of operation
        }
    });
}

private async void btnStart_Click(object sender, EventArgs e)
{
    List<string> list = new List<string>();
    for (int i = 0; i < 1000; i++)
        list.Add(i.ToString());
    lblStatus.Text = "Working...";
    var progress = new Progress<ProgressReport>();
    progress.ProgressChanged += (o, report) => {
        lblStatus.Text = string.Format("Processing...{0}%", report.PercentComplete);
        progressBar.Value = report.PercentComplete;
        progressBar.Update();
    };
    await ProcessData(list, progress);
    lblStatus.Text = "Done !";
}

The progress.Report(i) method sends the current step to the progress handler, which updates the progress bar.

The progress bar is updated in the context of the UI thread, ensuring thread safety.

The Progress<T> class is key for safely updating UI elements from background threads.

Finally, Build and run the application, then click the button to start the operation, and observe the progress bar as it updates.

VIDEO TUTORIAL