async
:
html
使用 async
修飾符可將方法、lambda 表達式或匿名方法指定爲異步。 若是對方法或表達式使用此修飾符,則其稱爲異步方法express
await:編程
await
運算符應用於異步方法中的任務,在方法的執行中插入掛起點,直到所等待的任務完成,返回線程池。 任務表示正在進行的工做。多線程
區別:異步
執行流程:async
異步用例:ide
只有擁有async才能在其內部使用await關鍵字。異步方法能夠具備Task、Task<>或void的返回類型;異步編程
class Program { static void Main(string[] args) { Console.WriteLine("主線程測試開始.."); AsyncMethod(); Thread.Sleep(1000); Console.WriteLine("主線程測試結束.."); Console.ReadLine(); } static async void AsyncMethod() { Console.WriteLine("開始異步代碼"); var result = await MyMethod();//var result = MyMethod().Result Console.WriteLine("異步代碼執行完畢"); } static async Task<int> MyMethod() { for (int i = 0; i < 5; i++) { Console.WriteLine("異步執行" + i.ToString() + ".."); await Task.Delay(1000); //模擬耗時操做 } return 0; } }
Thread多線程異步編程例子:測試
class Program { static void Main(string[] args) { Console.WriteLine("主線程測試開始.."); Thread th = new Thread(ThMethod); th.Start(); Thread.Sleep(1000); Console.WriteLine("主線程測試結束.."); Console.ReadLine(); } static void ThMethod() { Console.WriteLine("異步執行開始"); for (int i = 0; i < 5; i++) { Console.WriteLine("異步執行" + i.ToString() + ".."); Thread.Sleep(1000); } Console.WriteLine("異步執行完成"); } }
參考: http://www.javashuo.com/article/p-pxxfsemu-q.html //線程池傳送門ui
http://www.javashuo.com/article/p-tqcehmav-w.html
http://www.javashuo.com/article/p-rivobvpq-bz.html
https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/async/