Multi-cast Delegate


Jump to: navigation, search

Contents

Summary

A multi-cast delegate is basically a list of delegates or a list of methods with the same signature. A multi-cast delegate can call a collection of methods instead of only a single method.

Remarks

.Net delegates are all multi-cast delegates. When calling a multi-cast delegate that returns a value, only the last value will be returned. In order to process every return value, iterate the delegate list and invoke each delegate individually.

If one of the methods throws an exception, the delegate call will immediately stop and no other methods in the list will be called.

Code examples

Adding multiple delegates to a delegate object

public delegate void ExecuteCallback();
 
class Executioner
{
	private ExecuteCallback _doExecute;
 
	public void AddMultiple()
	{
		// Add a delegate to MethodA
		// This will work even if _doExecute is currently null
		_doExecute += new Execute( MethodA );
 
		// Add a delegate to MethodB also
		_doExecute += new Execute( MethodB );
 
		// Add a delegate to MethodC also
		_doExecute += new Execute( MethodC );
	}
 
	public void MethodA()
	{
		//...
	}
 
	public void MethodB()
	{
		//...
	}
 
	public void MethodC()
	{
		//...
	}
}

Call a multi-cast delegate

// Call the delegate like a method
// This will automatically call each delegate that is part of this multi-cast delegate
doExecute();
		 
// Iterating through a multi-cast delegate manually
 
// Call each delegate in the multi-cast delegate one at a time
// In order to handle any exceptions that might occur
			
// Iterating through a delegate manually is needed in 
// order to continue processing all the delegates even 
// if one throws an exception
 
// In this example, any exceptions are ignored and 
// the processing continues with the next delegate
// In a real world example, the exception would at least be logged
 
public void IterateAll()
{
	if( _doExecute != null )
	{
		foreach( ExecuteCallback doSingleExecute in _doExecute.GetInvocationList() )
		{
			try
			{
				doSingleExecute();
			}
			catch
			{
				// This delegate threw an exception
			}
		}
	}
}
 
// This technique could also be used for other purposes:
// To get each return value if the delegate is not void
// To call all the delegates asynchronously
// Etc. 

See Also

Delegate Event


Share this page
  • del.icio.us
  • Facebook
  • Google+
  • StumbleUpon