// What is a delegate // ================== // A delegate is a type that represents references to methods with a particular parameter list and return type. public void Main() { //Assigning an existing function DoWorkDelegate doWorkDelegate = DoWork; //Assigning to an anonymous method (C# 2.0) DoWorkDelegate anonymousFunctionDelegate = delegate() { Console.WriteLine("Work done from anonymous function !"); }; //Assigning to an anonymous method (C# 3.0) DoWorkDelegate lambdaDelegate = () => Console.WriteLine("Work done from lambda expression !"); //Invoking a delegate's method doWorkDelegate.Invoke(); anonymousFunctionDelegate.Invoke(); lambdaDelegate.Invoke(); //Method chaining Console.WriteLine(); Console.WriteLine("Method chaining"); Console.WriteLine("=================="); doWorkDelegate += DoOtherWork; doWorkDelegate.Invoke(); //Using a delegate with params and a return type Console.WriteLine(); Console.WriteLine("Delegate with params and a return type"); Console.WriteLine("=================="); DoWorkAndReturnStuffDelegate delegateWithParamsAndReturnType = DoWorkAndReturnStuff; string result = delegateWithParamsAndReturnType.Invoke("Test input"); Console.WriteLine($"Delegate invocation result: {result}"); }
public void Demo01() { // DoWork(); Debug.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString()); DoWorkDelegate m = new DoWorkDelegate(DoWork); m.Invoke(); AsyncCallback callback = new AsyncCallback(TheCallback); IAsyncResult ar = m.BeginInvoke(callback, m); //// do more ar.AsyncWaitHandle.WaitOne(); }