sync 異步編程

 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 }
View Code

 

 

https://www.cnblogs.com/yaopengfei/p/9249390.htmlhtml

 

 

執行異步方法的時候有幾個注意事項dom

1.sync與await要成對出現,異步方法只能有3個返回值 (void Task 與 Task<T>)異步

2.異步方法內要自行經過task.run開闢新的線程出來async

3.主線程經過調用異步方法task.Resutl來獲取線程結果,此時也會阻塞線程等待結果ide

相關文章
相關標籤/搜索