Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A Generic Method for Cross-thread Winforms Access

0.00/5 (No votes)
18 Jun 2009 1  
A convenient shortcut using generics to check for InvokeRequired on a Winforms control

Introduction

When writing a WinForms app, one is likely to encounter the scenario where he/she must access a Form control from another thread, such as from the Timer.Interval event. To do so, the Control.InvokeRequired property must be checked, and if true, the control access must be done using a delegate from the Control.Invoke method. 

An example of this would be as follows:

void UpdateLabel(Label lbl, String text)
{
    if (lbl.InvokeRequired)
    { lbl.Invoke(new Action<Label, String>(UpdateLabel), new object[] { lbl, text }); }
    else
    { lbl.Text = text; }
}

While this works, it requires a separate method to be written for each control type, and for each action that you wish to execute from another thread.

To encapsulate this cross-thread access behavior, we turn to Generics.

Using the Code

We will use the following generic utility method to perform all cross-thread control manipulation:

public static void InvokeControlAction<t>(t cont, Action<t> action) where t : Control
{
    if (cont.InvokeRequired)
    { cont.Invoke(new Action<t, Action<t>>(InvokeControlAction), 
				new object[] { cont, action }); }
    else
    { action(cont); }
}

To elaborate:

  • t is the type of control that we wish to access, such as Label
  • cont is the instance of our control which we will be manipulating.
  • action is a generic delegate void which accepts an instance of t. By using a generic delegate, we can define the properties/methods we want to access on our instance of t in the calling code, instead of assuming the control type and action in a method as we did before.
  • Finally, t must inherit Control in order for us to check on the InvokeRequired property.

So we execute as follows:

  1. If cont.InvokeRequired evaluates to true, call cont.Invoke with a new generic Action<> delegate that fits the signature of InvokeControlAction<t> and pass cont and action right back in recursively.
  2. If cont.InvokeRequired evaluates to false (either step 1 was executed or this method was called from the same thread which contains cont), we execute the delegate action, passing in our control instance... cont.

To use this method in a real world example: In our Clock application, we have a timer which ticks every second. Here is the Elapsed event handler, where we make use of our utility method:

void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    //On tick, update the time
    CrossThreadUtility.InvokeControlAction<Label>
	(lblTime, lbl => lbl.Text = String.Format("The current time is: {0}", 
	DateTime.Now.ToString("h:mm:ss tt")));
}

Here, we pass our Label lblTime as cont, and for the delegate action we use C# 3.0's Lambda Expression feature to code our delegate in-line for a nice clean one-liner.

The action we perform on lblTime, (in the context of lbl in the lambda expression) is simple:

lbl.Text = String.Format("The current time is: {0}", 
			DateTime.Now.ToString("h:mm:ss tt"))

Points of Interest

You can easily substitute Label for any Windows Forms control type... try this to make the time show up on the Form's title bar instead of the Label lblTime:

CrossThreadUtility.InvokeControlAction<Form>(this, frm => frm.Text = 
    String.Format("The current time is: {0}", DateTime.Now.ToString("h:mm:ss tt")));

Conclusion

We have created a utility method for clean one-line cross-thread control access, regardless of control type or access action.

History

  • 18th June, 2009: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here