Click here to Skip to main content
Click here to Skip to main content

A Generic Method for Cross-thread Winforms Access

, 18 Jun 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

colonel720
Software Developer Self Employed
United States United States
Avi is a passionate developer; working for himself doing custom application development for multiple industries using c# and the .net framework.
Developing creative solutions for coding challenges is one of his favorite activities.

Comments and Discussions

 
GeneralExtension Method Implementation PinmemberShannon McCoy1-May-11 0:00 
GeneralRe: Extension Method Implementation Pinmembersage4523-Jun-11 11:43 
Generalmulticommand Pinmemberchfunglukas18-Nov-10 0:43 
GeneralRe: multicommand PinmemberScottK725-Apr-11 6:51 
QuestionWhat about a return type? PinmemberMember 403088927-Sep-10 13:16 
GeneralVB.NET PinmemberJessieBurns8-Jun-10 8:41 
GeneralRe: VB.NET Pinmembersage4523-Jun-11 11:36 
GeneralAnother method PinmemberPaul B.22-Jun-09 13:10 
GeneralMaking use of extension methods PinmemberD-Lay18-Jun-09 3:31 
GeneralRe: Making use of extension methods Pinmembercolonel72023-Jun-09 12:04 
GeneralOh, and one point PinmemberRob Philpott18-Jun-09 2:44 
GeneralRe: Oh, and one point Pinmembercolonel72023-Jun-09 12:01 
GeneralNice solution PinmemberRob Philpott18-Jun-09 2:41 
GeneralMy vote of 5 [modified] PinmemberAnt210018-Jun-09 0:51 
GeneralRe: My vote of 5 Pinmembercolonel72023-Jun-09 11:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141223.1 | Last Updated 18 Jun 2009
Article Copyright 2009 by colonel720
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid