Monday 25 November 2013

Winforms - Update UI for Long running processes

If you have a long running process in your windows forms application you might try to update a message label in the UI to say "Processing. Please wait...". But as a matter or fact, the UI doesn't get updated till the process is completed. in this case it doesn't serve your purpose of notifying the user by updating a UI element.
private void btnAzerbaijanReportJob_Click(object sender, EventArgs e)
{
lblMessage.Text = "Please wait..";
IneedTime(); // Long running process.
lblMessage.Text = "Done.";
}
In the above case, lblMessage will never display the text "Please wait..", because IneedTime() method executes on the UI thread and UI will not be updated until IneedTime() methods finish executing.
To overcome this, there are 2 methods.
1) Run long running process (IneedTime() in the above code) in a separate thread. In case you dislike to make your app a multi thread app, you have a second option.
2) Second option is to force the UI to redraw the UI even before your long running method executes. For this you need to call the
Application.DoEvents() method. What this method does it that it will process all the windows messages currently in the message queue. So this queue will already have the paint message which was issued when we set the label (lblMessage) text.
private void btnAzerbaijanReportJob_Click(object sender, EventArgs e)
{
lblMessage.Text = "Please wait..";
Application.DoEvents();
IneedTime(); // Long running process.
lblMessage.Text = "Done.";
}
In case you see the UI is not updated as expected, you can also use the below code.
lbl.Invalidate();
lbl.Update();
Application.DoEvents();
or even
lbl.Refresh();
Application.DoEvents();
to redraw the label UI.

No comments:

Post a Comment