Monday, July 13, 2009

Updating the User Interface in a thread safe manner in .Net

By default the user interface of any Windows application is managed on separate UI thread by the .Net framework. Apparently it appears to make an application's look and feel more responsive but sometimes it causes things to mess up a bit when developing an application in which there are a lot of multiple threads involved in updating the UI and the framework immediately throws an exception if you try to make other threads update the controls on the UI.
Thankfully there is a simple solution to this, seemingly, complex problem. The key here is to use .Net delegates or in "layman" terms delegate the task to be performed by one thread to the UI thread instead.
First, you would need to create a method that updates the UI as per required for instance:


public void UpdateUI(string anydata)
{

listBox1.Items.Add(anydata);

}

Then create a delegate and assign it the above method.
//Declaring delegate
public delegate void UpdateData(string anyData);

//The signature of your delegate must be similar to the UpdateUI method

and finally instantiating the delegate

UpdateData UpdateDelegate = new UpdateData(UpdateUI);

Now you may call this delegate in any method that any of your thread may be executing as under:

public void SomeThreadedMethod()
{
//some code...
.
.
this.Invoke(UpdateDelegate,anydata);
.
.
}

No comments:

Post a Comment