Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force GUI update from UI Thread

In WinForms, how do I force an immediate UI update from UI thread?

What I'm doing is roughly:

label.Text = "Please Wait..." try  {     SomewhatLongRunningOperation();  } catch(Exception e) {     label.Text = "Error: " + e.Message;     return; } label.Text = "Success!"; 

Label text does not get set to "Please Wait..." before the operation.

I solved this using another thread for the operation, but it gets hairy and I'd like to simplify the code.

like image 242
dbkk Avatar asked Sep 01 '09 07:09

dbkk


People also ask

Can we update UI from thread?

In this case, to update the UI from a background thread, you can create a handler attached to the UI thread, and then post an action as a Runnable : Handler handler = new Handler(Looper. getMainLooper()); handler. post(new Runnable() { @Override public void run() { // update the ui from here } });

How do you handle the UI update from multiple threads?

1) Have each thread set a "DataUpdated" flag when new data is available, and have the UI periodically check for new data. 2) Create each thread with a callback to a UI Update(...) method to be called when new data becomes available.


1 Answers

At first I wondered why the OP hadn't already marked one of the responses as the answer, but after trying it myself and still have it not work, I dug a little deeper and found there's much more to this issue then I'd first supposed.

A better understanding can be gained by reading from a similar question: Why won't control update/refresh mid-process

Lastly, for the record, I was able to get my label to update by doing the following:

private void SetStatus(string status)  {     lblStatus.Text = status;     lblStatus.Invalidate();     lblStatus.Update();     lblStatus.Refresh();     Application.DoEvents(); } 

Though from what I understand this is far from an elegant and correct approach to doing it. It's a hack that may or may not work depending upon how busy the thread is.

like image 151
Jagd Avatar answered Sep 18 '22 18:09

Jagd