using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace AnsyTestApp { class Program { static void Main(string[] args) { //Action actInt=TestVote; //foreach (Action item in actInt.GetInvocationList()) //{ // item(); //} // DeleteGateTest(); // WaitHandDelegateTest(); AnsyCallBackTest();//异步回调条件是必须是主线程一直 存在才可以执行 回调函数否则不执行 for (int i = 0; i < 100; i++) { Console.WriteLine("等待执行异步回调的方法"); Thread.Sleep(100); } } public delegate int AsyTestDelegate(int t1, int t2); /// <summary> /// 异步委托投票执行 /// </summary> static void DeleteGateTest() { AsyTestDelegate asyDelegate = TaskReturnTest; IAsyncResult ar = asyDelegate.BeginInvoke(11, 22,null, null); while (!ar.IsCompleted) { ///如果异步委托没有结束任务就一直执行这里 ReturnConsole("异步委托还没有完成"); Thread.Sleep(50); } int result = asyDelegate.EndInvoke(ar); ReturnConsole(result); } /// <summary> /// 等待句柄异步委托(可以设置过期时间) /// </summary> static void WaitHandDelegateTest() { AsyTestDelegate dl = TaskReturnTest; IAsyncResult ar = dl.BeginInvoke(33, 44, null, null); ReturnConsole("等待句柄异步操作"); while (!ar.IsCompleted) { ReturnConsole("等待ing"); if (ar.AsyncWaitHandle.WaitOne(1000,false)) { ReturnConsole("等到异步委托执行完毕了"); break; } } int result = dl.EndInvoke(ar); ReturnConsole(result); } /// <summary> /// 异步回调委托 /// </summary> static void AnsyCallBackTest() { AsyTestDelegate dl = TaskReturnTest; IAsyncResult ar = dl.BeginInvoke(55, 66, AnsyDelegateComplete, dl); } /// <summary> /// 异步回调调用方法 /// </summary> /// <param name="ar"></param> static void AnsyDelegateComplete(IAsyncResult ar) { if (ar==null) { ReturnConsole("ar is null"); } AsyTestDelegate dl = ar.AsyncState as AsyTestDelegate; Trace.Assert(dl != null, "Invalid object type"); int result = dl.EndInvoke(ar); ReturnConsole(result); } static int TaskReturnTest(int da,int ms) { ReturnConsole("TaskReturnTest Start"); Thread.Sleep(TimeSpan.FromSeconds(2)); ReturnConsole("TaskReturnTest Completed"); return ++da; } /// <summary> /// 闲的蛋疼的封转 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="tmsg"></param> static void ReturnConsole<T>(T tmsg) { Console.WriteLine(tmsg); } static void Test(string a1){ } static void TestVote() { Console.WriteLine("TestVote ass"); } } }
各有千秋