1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading; 6 using System.Threading.Tasks; 7 8 namespace ConAppAsync 9 { 10 class Program 11 { 12 13 //第一步,创建一个普通的耗时的方法 14 static string Greeting(string name) 15 { 16 Thread.Sleep(3000); 17 return String.Format("Hello, {0}", name); 18 } 19 20 //第二步,用一个异步方法包装上面的方法 21 static Task<string> GreetingAsync(string name) 22 { 23 return Task.Run<string>(() => 24 { 25 return Greeting(name); 26 }); 27 } 28 29 //第三步,再创建一个能调用上面的异步方法的方法, 加关键字 async 30 31 private async static void CallWithAsync() 32 { 33 //some other tasks 34 35 string result = await GreetingAsync("王海滨"); 36 37 //we can add multiple "await" in same "async" method 38 string result1 = await GreetingAsync("Ahmed"); 39 string result2 = await GreetingAsync("Every Body"); 40 Console.WriteLine(result+result1+result2); 41 } 42 43 static void Main(string[] args) 44 { 45 //最后在主入口调用上面的方法,和调用普通方法一样 46 CallWithAsync(); 47 int length = 100; 48 for (int i = 0; i < length; i++) 49 { 50 Console.WriteLine(i); 51 } 52 Console.ReadKey(); 53 } 54 } 55 }