.Net 非同步隨手記(一)

來源:互聯網
上載者:User

標籤:

今天要記錄的內容摘要是:

什麼時候非同步代碼能“等”在那裡,什麼時候不會“等”

 

這兩天Coding的時候碰到一個事兒,就是想讓非同步等在那裡結果卻直接執行過去了,比如這樣:

 1         async static void Count() 2         { 3             Console.WriteLine("Task Void 開始"); 4             Console.WriteLine(Thread.CurrentThread.ManagedThreadId); 5             int count = 0; 6             while (count < 10) 7             { 8                 Console.WriteLine("Print value:{0}", count); 9                 count++;10                 await Task.Delay(500);11             }12             Console.WriteLine("Task Void 結束");13         }

 

接下來寫這兩句:

1 var taskVoid = new Task(Count);2 await taskVoid;

 

哈哈,原本按照其它非同步方式去寫的時候比如 await HttpClient.GetAsync(); 是非常正常的,程式的邏輯會停在這一句,直到獲得結果才會進行下面的語句。但運行 await taskVoid 後,會立即運行下面的語句,這是怎麼回事?經過仔細檢查發現是因為 Count 方法沒有傳回值,是 void ,因此必須要加以改造。如果 Count 方法傳回值是 Task ,await 才能起效,比如改成這樣:

 1         static void Main(string[] args) 2         { 3             Entry(); 4             Console.ReadLine(); 5              6         } 7  8         async static Task CountAsync() 9         {10             Console.WriteLine("Task Void 開始");11             int count = 0;12             while (count < 10)13             {14                 Console.WriteLine("Print value:{0}", count);15                 count++;16                 await Task.Delay(500);17             }18             Console.WriteLine("Task Void 結束");19         }20 21         async static void Entry()22         {23             // 建立一個無參數無傳回值的方法24             var taskVoid = Task.Factory.StartNew(CountAsync);25 26             await taskVoid.Result;27             // 建立一個 taskVoid 之後才能啟動並執行方法28             var taskContinue = taskVoid.ContinueWith(async (t) =>29             {30 31                 Console.WriteLine("這是在 TaskVoid 運行之後才能啟動並執行 TaskContinue,Task void 的狀態是 {0}", t.Status);32                 await Task.Delay(1000);33             });34             ;35         }
改造後的非同步

 

個人理解:

await 作為文法糖,起作用的對象是 Task ,void 方法返回的不是 Task 自然對之前的寫法來講不起作用。Task 用一個“新線程” 去執行 void 方法,自然立即就“返回”了,但返回並不表示方法結束了,方法內還是按照自己的邏輯去運行了,所以這個時候我只能眼巴巴看著 void 類型的 Count 返回卻無力控制它。改成後面的寫法之後,改造後的 CountAsync 方法返回的是 Task,意思是告訴上層“我是一個Task”,這個時候 await 就可以起作用了。但直接寫 await taskVoid 依舊不能起作用,因為此時 taskVoid 無傳回值,也就是立即返回了,所以必須要寫成“var taskVoid = Task.Factory.StartNew(CountAsync)” + "await taskVoid.Result"的方式,StartNew 方法會內部建立一個 Task 並返回,這個 Task 的傳回值是 CountAsync,而 Result 表示了“我要等待運行 CountAsync 這個非同步任務的非同步任務的結果返回來”。因此,await 起了作用,執行順序正確了。

本人學藝不精,對 .Net 內部基本沒什麼涉獵,如有老鳥看到希望能提出指正意見,謝謝。

.Net 非同步隨手記(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.