Windows Forms: Progress Bar in C#
By FoxLearn 2/20/2024 6:22:17 AM 6.49K
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
- Windows Forms: Text to speech in C#
- Windows Forms: Print Picture Box in C#
- Windows Forms: Advanced Filter DataGridView in C#
- How to create a Lucky Draw games in C#
- Windows Forms: Youtube Search with Paging in C#
- Windows Forms: How to Create a Random Password Generator in C#
- Windows Forms: Tag Control in C#
- Windows Forms: Wait Form Dialog in C#
Categories
Popular Posts
Visual Studio: Auto increment version
04/01/2024
What is ARM architecture?
04/01/2024