Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

.NET

Threading & .NET


Updating the UI

Throughout its history, a fundamental rule of Windows UI programming has been: "Only access a UI element on the thread that created it." This is the result of how Windows sends messages to UI elements. When dealing with multiple threads, it is important to remember this rule. Table 2 lists the members of Control-derived classes that can be accessed on any thread. All other members must be accessed on the thread that created the UI element.

Members
BeginInvoke()
CreateGraphics()
EndInvoke()
Invoke()
InvokeRequired()

Table 2: Control members callable on any thread.

Events are often used to notify users about important changes in the system. When an event is raised on a secondary thread, it is not possible to update the UI directly. Instead, any UI changes must be marshaled to the thread that created the UI element. In .NET, the InvokeRequired property on any Control-derived class determines whether the UI element can be directly updated. When this property is false, all UI access must be marshaled to the appropriate thread. There is a special case when the control has not yet been created (see forums.microsoft.com/MSDN/ShowPost.aspx?PostID=170601&SiteID=1). However, it is generally reliable.

To marshal a property or method call to the appropriate thread, use the Invoke() method on the Control-derived class. This method requires the name of the delegate to invoke and the parameters to pass to the delegate. When called, the method marshals the invocation to the associated UI thread and waits for it to return. An asynchronous version is also available if needed. Listing Four provides sample code on how to use Invoke(). By changing the delegate, parameters, and member names, this template can be used for any method or property call. Furthermore, the same method is called whether an invocation is required or not.

 
//Create a delegate that matches the signature of the method to invoke
void MyDelegate ( object parm1, string parm2 );

//The method that is invoked by clients on any thread
//"control" is the UI element
void MyMethod ( object parm1, parm2 )
{
	//If called on a thread other than the UI thread
	if (control.InvokeRequired)
	{
		//Marshal the request to the UI thread, could use BeginInvoke too
		//Notice the delegate is the same method
		control.Invoke(new MyDelegate(MyMethod), parm1, parm2);
	} else
	{
		//On the UI thread so do any work here...
	};
}
Listing Four

The invocation code is normally placed inside an event handler. For example, if a work item raises an event, any handler that wants to update the UI needs to use the invocation code. It is recommended that a control not try to deal with the threading issue automatically (by using the invocation code inside its property and method blocks) as this needlessly complicates the control and may mislead a caller. Any caller that interacts with a control is responsible for dealing with the threading issue.

Introduced in .NET 2.0, the BackgroundWorker class (msdn2.microsoft.com/en-us/library/4852et58.aspx) was specifically designed to permit applications to perform some work on a secondary thread and still be able to update UI elements without the need for the invocation code. This class is an ideal solution in most cases and should be used instead. However, the created thread can only be canceled. Therefore, only use this class if pause/resume support is not needed. DDJ


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.