Click here to Skip to main content
15,885,914 members
Articles / Desktop Programming / Windows Forms

A Generic Method for Cross-thread Winforms Access

Rate me:
Please Sign up or sign in to vote.
4.93/5 (20 votes)
17 Jun 2009CPOL2 min read 77.8K   1.2K   57   18
A convenient shortcut using generics to check for InvokeRequired on a Winforms control
Image 1

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:

C#
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:

C#
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:

C#
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:

C#
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:

C#
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)


Written By
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

 
QuestionNice work, got my 5 Pin
Mike Hankey19-Jan-24 4:18
mveMike Hankey19-Jan-24 4:18 
QuestionChange required Pin
mbv40192015017-Mar-15 13:40
mbv40192015017-Mar-15 13:40 
GeneralAwesome!!! - Thank you for share!!! Pin
mbv40192015017-Mar-15 13:11
mbv40192015017-Mar-15 13:11 
GeneralExtension Method Implementation Pin
Shannon McCoy30-Apr-11 23:00
Shannon McCoy30-Apr-11 23:00 
GeneralRe: Extension Method Implementation Pin
sage4523-Jun-11 10:43
sage4523-Jun-11 10:43 
Generalmulticommand Pin
chfunglukas17-Nov-10 23:43
chfunglukas17-Nov-10 23:43 
GeneralRe: multicommand Pin
ScottK725-Apr-11 5:51
ScottK725-Apr-11 5:51 
QuestionWhat about a return type? Pin
Member 403088927-Sep-10 12:16
Member 403088927-Sep-10 12:16 
GeneralVB.NET Pin
JessieBurns8-Jun-10 7:41
JessieBurns8-Jun-10 7:41 
GeneralRe: VB.NET Pin
sage4523-Jun-11 10:36
sage4523-Jun-11 10:36 
GeneralAnother method Pin
Paul B.22-Jun-09 12:10
Paul B.22-Jun-09 12:10 
GeneralMaking use of extension methods Pin
Daniel Kailer18-Jun-09 2:31
Daniel Kailer18-Jun-09 2:31 
GeneralRe: Making use of extension methods Pin
colonel72023-Jun-09 11:04
colonel72023-Jun-09 11:04 
GeneralOh, and one point Pin
Rob Philpott18-Jun-09 1:44
Rob Philpott18-Jun-09 1:44 
GeneralRe: Oh, and one point Pin
colonel72023-Jun-09 11:01
colonel72023-Jun-09 11:01 
GeneralNice solution Pin
Rob Philpott18-Jun-09 1:41
Rob Philpott18-Jun-09 1:41 
GeneralMy vote of 5 [modified] Pin
Anthony Daly17-Jun-09 23:51
Anthony Daly17-Jun-09 23:51 
GeneralRe: My vote of 5 Pin
colonel72023-Jun-09 10:57
colonel72023-Jun-09 10:57 

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

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