UI Threading

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies.
This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.
To create client business applications using current Microsoft technologies, see patterns & practices' Prism.

Problem

Frequently, a smart client application performs some operations on a background thread. It performs other operations on the same thread as the user interface. In both cases, when an operation completes, the application must update the user interface. However, Windows applications can update UI controls only from the UI thread. In those cases, the application must marshal control back to the UI thread.

Solution

Create a private method in the view class to update the user interface. Define a delegate with the same signature as the private method. Create a public method that the presenter calls to request the view to update the user interface. In this public method, write code to marshal control to the UI thread when necessary. You can use the InvokeRequired property of the view to determine whether you must marshal control to the UI. If InvokeRequired returns true, use BeginInvoke (you can also use Invoke) to call the private method through a new delegate, as shown in the following code.

private delegate void UpdateStatusDelegate(string status);

public void UpdateStatus(string status)
{
if (InvokeRequired)
    BeginInvoke(new UpdateStatusDelegate(InnerUpdateStatus), new object[] { status });
else
    InnerUpdateStatus(status);
}

private void InnerUpdateStatus(string status)
{
  // This is code to update the UI.
}