Windows Forms: Progress Bar in C#
By FoxLearn 2/20/2024 6:22:17 AM 6.67K
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 1: 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
Step 2: Design your form as below
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
- How to Send and Receive email in Microsoft Outlook using C#
- How to Print Windows Form in C#
- How to Use Form Load and Button click Event in C#
- How to use Advanced Filter DataGridView in C#
- How to use TagListControl in C#
- How to use Error Provider in C#
- How to Drag and Drop controls in C#
- How to Create a Random Password Generator in C#