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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With