Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GUI not updating until code is finished

Tags:

c#

label

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?

like image 779
Andy Hin Avatar asked Oct 18 '10 12:10

Andy Hin


2 Answers

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.

like image 129
Mark Byers Avatar answered Oct 12 '22 12:10

Mark Byers


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:

  • Use a BackgroundWorker
  • Call 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.

like image 33
GvS Avatar answered Oct 12 '22 13:10

GvS