1 using System; 2 using System.Net; 3 using System.Threading; 4 using System.Threading.Tasks; 5 6 7 namespace ConsoleApp1 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 Console.WriteLine($"Main Start...{System.Threading.Thread.CurrentThread.GetHashCode()}"); 14 15 var rst = DisplayValueAsync(); 16 17 Console.WriteLine($"Main do some thing End...{System.Threading.Thread.CurrentThread.GetHashCode()}"); 18 19 Console.WriteLine($"Sub1 End...values is {rst.Result} {System.Threading.Thread.CurrentThread.GetHashCode()}"); 20 21 Console.Read(); 22 23 24 } 25 26 27 public static async Task<int> DisplayValueAsync() 28 { 29 Console.WriteLine($"Sub call...{System.Threading.Thread.CurrentThread.GetHashCode()}"); 30 31 var rst= await Task<int>.Run(()=> { 32 33 System.Threading.Thread.Sleep(2000); 34 35 Console.WriteLine($"Sub exec...{System.Threading.Thread.CurrentThread.GetHashCode()}"); 36 37 38 var random = new Random(); 39 return random.Next(1,1000); 40 41 }); 42 43 return rst; 44 45 } 46 47 48 49 } 50 51 }
https://www.cnblogs.com/yaopengfei/p/9249390.html
执行异步方法的时候有几个注意事项
1.sync与await要成对出现,异步方法只能有3个返回值 (void Task 与 Task<T>)
2.异步方法内要自行通过task.run开辟新的线程出来
3.主线程通过调用异步方法task.Resutl来获取线程结果,此时也会阻塞线程等待结果