1. 實例1
1.1 代碼
using System ;
using System. Collections. Generic ;
using System. Linq ;
using System. Text ;
using System. Threading. Tasks ; namespace ConsoleApp1
{ class Program { static void Main ( string [ ] args) { Method1 ( ) ; Method2 ( ) ; Console. ReadKey ( ) ; } public static async Task Method1 ( ) { Console. WriteLine ( "Method 1 Start................" ) ; await Task. Run ( ( ) => { for ( int i = 0 ; i < 100 ; i++ ) { Console. WriteLine ( " Method 1" ) ; } } ) ; Console. WriteLine ( "Method 1 End................" ) ; } public static void Method2 ( ) { for ( int i = 0 ; i < 25 ; i++ ) { Console. WriteLine ( " Method 2" ) ; } } }
}
1.2 運行結果
Method2
不會等待Method1
運行結束再運行。async
方法中,await
后面的代碼也要等待await
運行結束以后再運行。
2. 實例2
2.1 代碼
using System ;
using System. Collections. Generic ;
using System. Linq ;
using System. Text ;
using System. Threading. Tasks ; namespace ConsoleApp2
{ class Program { static void Main ( string [ ] args) { callMethod ( ) ; Console. ReadKey ( ) ; } public static async void callMethod ( ) { Task< int > task = Method1 ( ) ; Method2 ( ) ; int count = await task; Method3 ( count) ; } public static async Task< int > Method1 ( ) { int count = 0 ; await Task. Run ( ( ) => { for ( int i = 0 ; i < 100 ; i++ ) { Console. WriteLine ( " Method 1" ) ; count += 1 ; } } ) ; return count; } public static void Method2 ( ) { for ( int i = 0 ; i < 25 ; i++ ) { Console. WriteLine ( " Method 2" ) ; } } public static void Method3 ( int count) { Console. WriteLine ( " Method 3 Total count is " + count) ; } }
}
2.2 運行結果
方式1的運行結果
3. 總結
調用async
方法且不使用await
修飾,不阻塞,直接運行。 調用async
方法且使用await
修飾,阻塞等待,直到運行完成再運行后面的代碼。
參考:
深入解析C#中的async和await關鍵字 C# 中的Async 和 Await 的用法詳解