一个简单的类理解清楚 Async/Await

项目下,一个同事遇到一个问题,关于Async/Await使用时导致的,花了一点时间写了一个简单的类帮他理解async是否开启线程、是否同步执行。分享到这里。

可将此代码粘贴到linqpad中执行

 1 void Main()
 2 {
 3     ("主线程ID="+ Thread.CurrentThread.ManagedThreadId.ToString()).Dump();
 4     new MyClass();
 5 }
 6 
 7 public class MyClass  
 8 {  
 9    public MyClass()  
10    {  
11        DisplayValue(); //这里不会阻塞  
12        ("myclass 类 threadid="+ Thread.CurrentThread.ManagedThreadId.ToString()).Dump();
13    }  
14    public Task<double> GetValueAsync(double num1, double num2)  
15    {   
16           System.Threading.Thread.Sleep(3000);
17        return Task.Run(() =>  
18        {  
19            for (int i = 0; i < 1000000; i++)  
20            {  
21                num1 = num1 / num2;  
22            }  
23             ("GetValueAsync  线程ID="+ Thread.CurrentThread.ManagedThreadId.ToString()).Dump();
24            return num1;  
25        });  
26       
27    }  
28    public async void DisplayValue()  
29    {  
30         ("DisplayValue进入时的线程 threadid="+ Thread.CurrentThread.ManagedThreadId.ToString()).Dump();
31            double result = await GetValueAsync(1234.5, 1.01);//此处会开新线程处理GetValueAsync任务,然后方法马上返回  
32         string.Format(" 计算结果 :[{0}]",result).Dump();
33 
34         ("DisplayValue结束时 threadid="+ Thread.CurrentThread.ManagedThreadId.ToString()).Dump();
35    }  
36 }

linqpad的执行结果如下

主线程ID=24
DisplayValue进入时的线程 threadid=24
myclass 类 threadid=24
GetValueAsync  线程ID=21
 计算结果 :[2.47032822920623E-322]
DisplayValue结束时 threadid=21

参考微软官方链接

posted @ 2017-04-14 13:40  Joseph zheng  阅读(431)  评论(0编辑  收藏  举报