Chained Delegates

Delegate chaining allows you to create a linked list of delegates such that when the delegate at the head of the list is called, all of the delegates in the chain are called. The System.Delegate class provides a few static methods to manage lists of delegates.

Delegate.Combine(), Delegate.Remove() & Delegate.RemoveAll()

  • The result that comes out from chained invocation is the result of the last delegate.
  • Any exception in chained invocation terminates the chained invocation process.
  • You can also pass value by reference, but be aware that each delegate that uses the reference parameter will see the changes made by the previous delegate in the chain.
  • Before invoking the delegate chain, you must cast the delegate back into the explicit delegate type.

Code…

   public delegate int ProgressChanged(int value);        
   
public class TestChainedInvocation     
  
{
     
      
public void Process()
     
      
{
                
             ProgressChanged[] ProgessDelegates=new ProgressChanged[]{
 
                 
new ProgressChanged(1),
 
                 
new ProgressChanged(2),
   
                
new ProgressChanged(3)};
   
             
ProgressChanged Result = (ProgressChanged)Delegate.Combine(ProgessDelegates);
                              
          
//simple invocation
  
           
Result.Invoke(10);
             
          
//OR
    
           
Result(10);
        
           
//Get invocation list
         
          
int Total;
     
          
foreach (ProgressChanged  ProgressDelegate in Result.GetInvocationList())
     
        
  {
     
              
Total+=ProgressDelegate.Invoke(2);
  
             
}
     
         
}
       
   
  }

Leave a Reply