The following code shows how to execute a method asynchronously using delegates and how a call-back method is executed when it is completed. As you run the code, you can see the Add method displays the sum of two numbers and wait for 3 seconds. Only then, the method call ends and executes the code in the addCompleted method.
delegate void deleType(int x, int y); public class Class1 { public void Add(int i, int j) { Console.WriteLine(i + j); System.Threading.Thread.Sleep(3000); } public void addCompleted(IAsyncResult result) { deleType deleInstance = (deleType) result.AsyncState; deleInstance.EndInvoke(result); if (result.IsCompleted == true) Console.WriteLine("Asynchronous call completed!"); } public static void Main() { Class1 c = new Class1(); deleType deleInstance = new deleType(c.Add); AsyncCallback cbackMethod = new AsyncCallback(c.addCompleted); IAsyncResult result = deleInstance.BeginInvoke(10, 20, cbackMethod, deleInstance); Console.WriteLine("Press Enter to close application."); Console.ReadLine(); } }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|