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 的用法详解