标签:
现在要实现异步只要用关键字async/await就可以轻松实现,在此之前需要用到委托/回调等一堆东西。
对一下是对比写法:
1 class Program 2 { 3 delegate string SendMessage(string msg); 4 static void Main(string[] args) 5 { 6 SendMessage sm = new SendMessage(DoAction); 7 sm.BeginInvoke("asyn asyn asyn ... ...", new AsyncCallback(CallBack), null); 8 9 DoAsync("async keywod.. ..."); 10 11 Console.WriteLine("do do do .... ..."); 12 13 Console.ReadLine(); 14 } 15 16 static void CallBack(IAsyncResult result) 17 { 18 SendMessage sm = (SendMessage)((System.Runtime.Remoting.Messaging.AsyncResult)result).AsyncDelegate; 19 Console.WriteLine(sm.EndInvoke(result)); 20 } 21 22 static string DoAction(string msg) 23 { 24 Thread.Sleep(3000); 25 return msg; 26 } 27 28 static Task<string> DoTask(string msg) 29 { 30 return Task.Run(() => 31 { 32 Thread.Sleep(1000); 33 return msg; 34 }); 35 } 36 37 static async void DoAsync(string msg) 38 { 39 Console.WriteLine(await DoTask(msg)); 40 }
标签:
原文地址:http://www.cnblogs.com/AspDotNetMVC/p/5699462.html