Resolved progress bar

aronmatthew

Active member
Joined
Aug 5, 2019
Messages
41
Programming Experience
Beginner
For some reason this is failing to update the percent label on the form....
prcentageLabelPost.png


percentage label not updating:
                percentLabel.Text = "0%";
                double percentage;
                for (int i = 0; i < sourceFiles.Count; i++)
                {

                    File.Copy(sourceFiles[i], targetFiles[i], true);
                  
                    progressBar.Increment(1);
                    percentage = (double)i / sourceFiles.Count;
                    percentLabel.Text = Math.Round(percentage * 100).ToString() + '%';

                }
                 percentLabel.Text = "100%";
 
Because you are updating the text within a tight loop which never yields to let paint messages get back to the form to paint the updated text.

And no, the correct solution is not to use Application.DoEvents(). That was a VB6 hack. Beware of hard to reproduce, hard to debug re-entrancy bugs if you go down that route.
 
One option is to call Refresh on the Label. That will force an immediate repaint of that control specifically. Just note that that will actually make the entire process take longer. Not sure the increase will be significant though.
 
One option is to call Refresh on the Label. That will force an immediate repaint of that control specifically. Just note that that will actually make the entire process take longer. Not sure the increase will be significant though

a call to refresh solved it. The File.Copy method must be recrursive...
 
No. File.Copy() is not recursive. It only copies one file -- synchronously. So when you call it, your thread blocks until it is done. Since the thread you are currently calling it on is the UI thread, then the UI thread effectively stops while the copy is happening. The UI thread needs to be running so that windows messages are pumped. When windows messages are flowing then things like paint events and mouse click and button click handling can happen.

For any long running processes, you should be doing those in another thread so that the UI thread is not blocked. Before the advent of async/awit the way to do that was to either start your own threads, or use the system thread pool, or use the background worker class. Most people opted for the latter.
 

Latest posts

Back
Top Bottom