Click here to Skip to main content
11,715,165 members (69,766 online)
Click here to Skip to main content

A Generic Method for Cross-thread Winforms Access

, 17 Jun 2009 CPOL 34.9K 742 56
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.

You may also be interested in...

Comments and Discussions

 
QuestionChange required Pin
mbv40192015017-Mar-15 13:40
membermbv40192015017-Mar-15 13:40 
GeneralAwesome!!! - Thank you for share!!! Pin
mbv40192015017-Mar-15 13:11
membermbv40192015017-Mar-15 13:11 
GeneralExtension Method Implementation Pin
Shannon McCoy30-Apr-11 23:00
memberShannon McCoy30-Apr-11 23:00 
GeneralRe: Extension Method Implementation Pin
sage4523-Jun-11 10:43
membersage4523-Jun-11 10:43 
Generalmulticommand Pin
chfunglukas17-Nov-10 23:43
memberchfunglukas17-Nov-10 23:43 
GeneralRe: multicommand Pin
ScottK725-Apr-11 5:51
memberScottK725-Apr-11 5:51 
QuestionWhat about a return type? Pin
Member 403088927-Sep-10 12:16
memberMember 403088927-Sep-10 12:16 
GeneralVB.NET Pin
JessieBurns8-Jun-10 7:41
memberJessieBurns8-Jun-10 7:41 
GeneralRe: VB.NET Pin
sage4523-Jun-11 10:36
membersage4523-Jun-11 10:36 
GeneralAnother method Pin
Paul B.22-Jun-09 12:10
memberPaul B.22-Jun-09 12:10 
GeneralMaking use of extension methods Pin
D-Lay18-Jun-09 2:31
memberD-Lay18-Jun-09 2:31 
GeneralRe: Making use of extension methods Pin
colonel72023-Jun-09 11:04
membercolonel72023-Jun-09 11:04 
GeneralOh, and one point Pin
Rob Philpott18-Jun-09 1:44
memberRob Philpott18-Jun-09 1:44 
GeneralRe: Oh, and one point Pin
colonel72023-Jun-09 11:01
membercolonel72023-Jun-09 11:01 
GeneralNice solution Pin
Rob Philpott18-Jun-09 1:41
memberRob Philpott18-Jun-09 1:41 
GeneralMy vote of 5 [modified] Pin
Ant210017-Jun-09 23:51
memberAnt210017-Jun-09 23:51 
GeneralRe: My vote of 5 Pin
colonel72023-Jun-09 10:57
membercolonel72023-Jun-09 10: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.150901.1 | Last Updated 18 Jun 2009
Article Copyright 2009 by colonel720
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid