異步的兩種寫法: async 與 BeginInvoke

如今要實現異步只要用關鍵字async/await就能夠輕鬆實現,在此以前須要用到委託/回調等一堆東西。異步

對一下是對比寫法:async

 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         }

 

相關文章
相關標籤/搜索