Windows Forms: Progress Bar in C#

How to use Task Parallel with Progress Bar in C#. The Task Parallel Library is based on the concept of a task, which represents an asynchronous operation

Step 1Click 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

progressbar in c#Step 2: Design your form as below

progress bar in c#

Step 3: 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 !";
}

VIDEO TUTORIALS