using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Runtime.Remoting.Messaging; namespace Async { public delegate int AddHandler(int a, int b); public class AddCls { public static int Add(int a, int b) { Console.WriteLine("开始计算:" + a + "+" + b); Thread.Sleep(3000); Console.WriteLine("计算完成!"); return a + b; } } public class Test { static void Main(string[] args) { //同步 //sync(); //异步 //async(); //异步回调 asyncCallBack(); } /// <summary> /// 同步 /// </summary> private static void sync() { Console.WriteLine("===== 同步调用 SyncInvokeTest ====="); AddHandler handler = new AddHandler(AddCls.Add); int result = handler.Invoke(1, 2); Console.WriteLine("继续做别的事情。。。"); Console.WriteLine("和等于:" + result); Console.ReadKey(); } /// <summary> /// 异步 /// </summary> private static void async() { Console.WriteLine("===== 异步调用 AsyncInvokeTest ====="); AddHandler handler = new AddHandler(AddCls.Add); IAsyncResult ir = handler.BeginInvoke(1, 2, null, null); Console.WriteLine("继续做别的事情。。。"); int result = handler.EndInvoke(ir); Console.WriteLine("和等于:" + result); Console.ReadKey(); } /// <summary> /// 异步回调 /// </summary> private static void asyncCallBack() { Console.WriteLine("===== 异步调用 AsyncInvokeTest ====="); AddHandler handler = new AddHandler(AddCls.Add); IAsyncResult ir = handler.BeginInvoke(1, 2, new AsyncCallback(callBack), "AsycState:OK"); Console.WriteLine("继续做别的事情。。。"); Console.ReadKey(); } /// <summary> /// 回调 /// </summary> private static void callBack(IAsyncResult ir) { AddHandler handler = (AddHandler)((AsyncResult)ir).AsyncDelegate; Console.WriteLine(handler.EndInvoke(ir)); Console.WriteLine(ir.AsyncState); } } }
时间: 2024-10-17 13:48:44