Mega Code Archive

 
Categories / C# Tutorial / Thread
 

Asynchronous Invocation Of Delegates

using System; using System.Collections.Generic; using System.Text; using System.Threading;     public delegate int MyDelegate();     public class ClassWithDelegate     {         public MyDelegate theDelegate;         public void Run()         {             for (; ; )             {                 if (theDelegate != null)                 {                     foreach (MyDelegate del in theDelegate.GetInvocationList())                     {                         del.BeginInvoke(new AsyncCallback(ResultsReturned), del);                     }                  }              }          }          private void ResultsReturned(IAsyncResult iar)         {             MyDelegate del = (MyDelegate)iar.AsyncState;             int result = del.EndInvoke(iar);             Console.WriteLine("Delegate returned result: {0}", result);         }     }     public class MyHandler     {         private int myCounter = 0;         public void Register(ClassWithDelegate theClassWithDelegate)         {             theClassWithDelegate.theDelegate += new MyDelegate(DisplayCounter);         }         public int DisplayCounter()         {             Thread.Sleep(10000);             Console.WriteLine("Done with work in DisplayCounter...");             return ++myCounter;         }     }     public class Test     {         public static void Main()         {             ClassWithDelegate theClassWithDelegate = new ClassWithDelegate();             MyHandler fs = new MyHandler();             fs.Register(theClassWithDelegate);             theClassWithDelegate.Run();         }     }