The correct way to implement progressbar in C #

I study winforms, and I set myself a simple goal - to make progress that goes from empty to full. Here is my depressing attempt:

public partial class Form1 : Form { static BackgroundWorker bw = new BackgroundWorker(); public Form1() { InitializeComponent(); bw.DoWork += bw_DoWork; bw.RunWorkerAsync(); } void bw_DoWork(object sender, DoWorkEventArgs e) { for(int i=0; i<100; ++i) { progressBar1.PerformStep(); Thread.Sleep(10); } } } 

I'm sure Thread.Sleep() reprehensible. How can I avoid this?

+4
source share
3 answers

You are already doing this almost right. BackgroundWorker has a built-in mechanism for reporting progress already.

 public Form1() { bw1.WorkerReportsProgress = true; bw1.ProgressChanged += bw1_ProgressChanged; bw1.DoWork += bw1_DoWork; bw1.RunWorkerAsync(); } private void bw1_DoWork(object sender, DoWorkEventArgs e) { var worker = sender as BackgroundWorker; while (workNotDone) { //Do whatever work worker.ReportProgress(CalculateProgressDonePercentage()); } } private void bw1_ProgressChanged(object sender, ProgressChangedEventArgs e) { //This is called on GUI/main thread, so you can access the controls properly progressBar.Value = e.ProgressPercentage; } 

If you, of course, are not trying to animate the progress bar without reporting any progress, then you should probably just use the Marquee type, which will automatically scroll through the progress bar without any action. Or just use the background thread with Thread.Sleep() .

+7
source

There is nothing wrong with calling Thread.Sleep in the background thread.
If it's a placeholder, you can safely replace it with the actual job.

However, you cannot manipulate the ProgressBar (or any other control) directly from the background thread.
Instead, you should use the built-in BackgroundWorker runtime functions to control the progress bar.

If you are just trying to animate a meaningless progressbasr, you should use WinForms Timer instead of BackgroundWorker .

+3
source

If you just want to test the UI update by completing the time compilation task, Thread.Sleep is fine. For non-trivial programs, you will always find some kind of task here.

However, you should not update the progress bar directly inside BackgroundWorker.DoWork , since Windows requires that the user interface update be called in the user interface thread, and not in the background. Instead, call the BackgroundWorker.ReportProgress method. Always update the user interface inside the BackgroundWorker.ProgressChanged event.

Here you can see an example: http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx

+1
source

All Articles