using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Runtime.Remoting.Messaging; namespace AsyncDelegates { class Program { delegate void MyDelegate(double width, double height, out double area, out double perimeter); static void Main(string[] args) { DemoPolling(); DemoCallback(); Console.WriteLine("Press any key to close the application..."); Console.ReadKey(); } private static void DemoPolling() { Console.WriteLine("Demonstrating Polling"); Console.WriteLine("====================="); // Create a delegate and call a method asynchronously. MyDelegate theDel = MyAsyncMethods.RectangleCalc; double area, perimeter; IAsyncResult ar = theDel.BeginInvoke(100, 200, out area, out perimeter, null, DateTime.Now); // Poll until the thread has completed. while (!ar.IsCompleted) { Console.WriteLine("{0} and I'm still waiting", DateTime.Now); Thread.Sleep(TimeSpan.FromSeconds(1)); } // Polling is complete, so get the method results. theDel.EndInvoke(out area, out perimeter, ar); Console.WriteLine("{0} and polling is complete.", DateTime.Now); Console.WriteLine("Area is {0}, perimeter is {1}", area, perimeter); Console.WriteLine("Object state: {0}", ar.AsyncState); } private static void DemoCallback() { Console.WriteLine("\nDemonstrating Callbacks"); Console.WriteLine("======================="); // Create a delegate and call a method asynchronously. MyDelegate theDel = MyAsyncMethods.CircleCalc; AsyncCallback callbackDel = new AsyncCallback(MyProcessAsyncResults); double area, perimeter; IAsyncResult ar = theDel.BeginInvoke(100, 100, out area, out perimeter, callbackDel, DateTime.Now); // Do some work on the main thread, if there's anything to do. for (int i = 0; i < 5; i++) { Console.WriteLine("{0} and I'm busy doing some work on the main thread", DateTime.Now); Thread.Sleep(TimeSpan.FromSeconds(1)); } // Now just wait for the background thread to complete. Console.WriteLine("{0} and I don't have anything else to do, so I'll just wait...", DateTime.Now); ar.AsyncWaitHandle.WaitOne(); Console.WriteLine("{0} and the background thread has finished", DateTime.Now); } // Callback method. private static void MyProcessAsyncResults(IAsyncResult ar) { // Downcast IAsyncResult interface into AsyncResult class type. AsyncResult result = (AsyncResult)ar; // Get our delegate from the AsyncResult object. MyDelegate theDelegate = (MyDelegate)result.AsyncDelegate; // Get the results of the asynchronous method. double area, perimeter; theDelegate.EndInvoke(out area, out perimeter, ar); Console.WriteLine("{0} and the callback has been called.", DateTime.Now); Console.WriteLine("Area is {0}, perimeter is {1}", area, perimeter); Console.WriteLine("Object state: {0}", ar.AsyncState); } } }