tags:

views:

105

answers:

4

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?

+11  A: 

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.

Mark Byers
Details on the [background worker class](http://bit.ly/a9VgVn) and an [example of how to use it](http://bit.ly/ailRTF)
Barry
A: 

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.

Jaymz
A: 

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:

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.

GvS
A: 

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:

  • move processing to other thread and face Invoke() situtations
  • call DoEvents() and allow gui to refresh between your DoWork calls
  • do all the Work and update later
Daniel Mošmondor