Click here to Skip to main content
15,891,513 members
Articles / Desktop Programming / Windows Forms

Generic InvocationHelper

Rate me:
Please Sign up or sign in to vote.
4.91/5 (21 votes)
8 Jun 2007CPOL6 min read 79K   246   62  
A generic class for providing thread-safe invocation of delegates. Can be used for (but not limited to) updating GUI elements from another thread.
/********************************************************************
 * InvocationHelper
 *	A generic class for providing thread-safe invocation of
 *	delegates.  Can be used for (but not limited to) updating GUI
 *	elements from another thread.
 * 
 * Edward Poore - mailto:ed.poore@gmail.com
 ********************************************************************
 * Disclaimer
 *	This code has been run so it does work.  However, it has not been
 *	thoroughly tested so use at your own risk.
 * 
 *	This code requires Generics, and therefore .NET 2.  I have no
 *	patience for any one who will try and run this on .NET 1.x.
 * 
 *  If you do try to do so then might I suggest you find another
 *	job/profession!
 * 
 * License
 *	Feel free to modify and use it where you want, commerical or
 *	otherwise.  However I would (like all others) like to be
 *	acknowledged somewhere.
 * 
 *	I'd also be curious to hear of any wierd and wacky places the
 *	code is used.  It'd be interesting to hear about even if it's
 *	not wierd and wacky :-).
 *******************************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;

namespace SpitfireSystems
{
	public static class InvocationHelper<T>
	{
		public static void Invoke(T eventHandler)
		{
			InvocationHelper<T>.Invoke(eventHandler, null);
		}
		public static void Invoke(T eventHandler, params object[] arguments)
		{
			// Check that T is a delegate type
			if (!(eventHandler is Delegate))
			{
				throw new ArgumentException(string.Format("Type {0} is not derived from {1}", eventHandler.GetType().Name, typeof(Delegate).Name));
			}
			// Cast the to a delegate now since it's needed later
			Delegate handler = (eventHandler as Delegate);
			int requiredParameters = handler.Method.GetParameters().Length;
			// Check that the correct number of arguments have been supplied
			if (requiredParameters != arguments.Length)
			{
				throw new ArgumentException(string.Format("{0} arguments provided when {1} {2} required.", arguments.Length, requiredParameters, ((requiredParameters == 1) ? "is" : "are")));
			}
			// Get a local copy of the invocation list in case it changes
			Delegate[] invocationList = handler.GetInvocationList();
			// Check that it's not null
			if (invocationList == null)
			{
				return;
			}
			// Loop through delegates and check for ISynchronizeInvoke
			foreach (Delegate singleCastDelegate in invocationList)
			{
				ISynchronizeInvoke synchronizeTarget = singleCastDelegate.Target as ISynchronizeInvoke;
				// Check to see if the interface was supported
				if (synchronizeTarget == null)
				{
					// Invoke delegate normally
					singleCastDelegate.DynamicInvoke(arguments);
				}
				else
				{
					// Invoke through synchronization interface
					synchronizeTarget.BeginInvoke(singleCastDelegate, arguments);
				}
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer PooreDesign
United Kingdom United Kingdom
Ed is a student who due to a form of cancer (now clear) took a year out before going to Imperial College, London to study Electronic Engineering.

His interests include shooting (clay-pigeon (shotgun), air-rifle and rifle), playing with his three labradors (Sandy, Rosie and Tundra), programming (most experienced in C# and C, although those are not the only ones), walking (has completed Gold Duke of Edinburgh's Award), playing games and reading.

He lives in two places on a 57 acre farm in West Waleswith the rest of the family during the holidays; and Greater London during term time.

Languages and Technologies: C#, C, VB6, VB.NET, XAML, (X)HTML, CSS, XSLT, Assembler (PIC), ASP.NET, WPF, Windows.Forms, ASP, VBScript, JavaScript, Pascal / Delphi, XML

Current Stuff:
1st Year MEng Electronics Engineering (Imperial College, London)

Comments and Discussions