Reputation: 31893
Hey, I have a sequence of code that goes something like this:
label.Text = "update 0";
doWork();
label.Text = "update 1";
doWork2();
label.Text = "update 2";
Basically, the GUI does not update at all, until all the code is done executing. How to overcome this?
Upvotes: 8
Views: 13525
Reputation: 19956
GUI cannot update while running your code that way. GUI on windows depend on message processing, and message processing is halted while you are in your code - no matter what you do with the labels, buttons and such, they will all be updated AFTER your code exits and main messaage loop of the form is processed.
You have several options here:
Upvotes: 0
Reputation: 52518
The UI updates when it get's a the WM_PAINT message to repaint the screen. If you are executing your code, the message handling routine is not execute.
So you can do the following to enable executing of the message handler:
Application.DoEvents()
The Application.DoEvents, calls the message handler, and then returns. It is not ideal for large jobs, but for a small procedures, it can be a much simpler solution, instead of introducing threading.
Upvotes: 3
Reputation: 6348
Currently, all of your processing is being performed on the main (UI) thread, so all processing must complete before the UI thread then has free cycles to repaint the UI.
You have 2 ways of overcoming this. The first way, which is not recommended, is to use
Application.DoEvents();
Run this whenever you want the Windows message queue to get processed.
The other, recommended, way: Create another thread to do the processing, and use a delegate to pass the UI updates back to the UI thread. If you are new to multithreaded development, then give the BackgroundWorker a try.
Upvotes: 0
Reputation: 838226
An ugly hack is to use Application.DoEvents
. While this works, I'd advise against it.
A better solution is to use a BackgroundWorker
or a seperate thread to perform long running tasks. Don't use the GUI thread because this will cause it to block.
An important thing to be aware of is that changes to the GUI must be made on the GUI thread so you need to transfer control back to the GUI thread for you label updates. This is done using Invoke
. If you use a BackgroundWorker you can use ReportProgress - this will automatically handle calling Invoke for you.
Upvotes: 15