zoukankan      html  css  js  c++  java
  • 一个简单的类理解清楚 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
    

    参考微软官方链接

  • 相关阅读:
    hdu5360 Hiking(水题)
    hdu5348 MZL's endless loop(欧拉回路)
    hdu5351 MZL's Border(规律题,java)
    hdu5347 MZL's chemistry(打表)
    hdu5344 MZL's xor(水题)
    hdu5338 ZZX and Permutations(贪心、线段树)
    hdu 5325 Crazy Bobo (树形dp)
    hdu5323 Solve this interesting problem(爆搜)
    hdu5322 Hope(dp)
    Lightoj1009 Back to Underworld(带权并查集)
  • 原文地址:https://www.cnblogs.com/joseph_zheng/p/6708437.html
Copyright © 2011-2022 走看看