zoukankan      html  css  js  c++  java
  • async,await与task.wait()或task.Result的区别

    你是否曾经与我一样不理解async,await与task.wait()或者task.Result的区别?

    接下来,一个Demo让你看出他们之间的区别。

      static void Main(string[] args)
            {
                Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:start");
    
                Test(); //不等待
                Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:end");
                Console.Read();
            }
    
            static Task<int> Sleep()
            {
                Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Sleep start");
                Thread.Sleep(1000);
                Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Sleep end");
                return Task.FromResult(100);
            }
            
            static Task<int> Test()
            {
                Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Test start");
                var a=Task.Run(Sleep).Result;//由上一篇文章可知Run将会在线程池内调度执行
                Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Test end");
                return Task.FromResult(a);
            }

    运行结果:

    1:start
    1:Test start
    4:Sleep start
    4:Sleep end
    1:Test end
    1:end

    由此可以看出Task.Result会阻塞主线程。

     static void Main(string[] args)
            {
                Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:start");
    
                TestAsync();//不等待
    
                Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:end");
                Console.Read();
            }
    
            static Task<int> Sleep()
            {
                Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Sleep start");
                Thread.Sleep(1000);
                Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Sleep end");
                return Task.FromResult(100);
            }
            
            static async Task<int> TestAsync()
            {
                Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Test start");
                var a = await Task.Run(Sleep);
                Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:Test end");
                return a;
            }

    运行结果:

    1:start
    1:Test start
    4:Sleep start
    1:end
    4:Sleep end
    4:Test end

    async,await不会阻塞主线程

  • 相关阅读:
    每日问题汇总:2016-3-28
    DataList、Repeater、GridView中的Checkbox取值问题
    长数字字符串逗号分隔
    文字环绕图片效果
    js图片放大镜 可动态更换图片
    动态页面生成静态页
    SQL按汉语拼音首字母排序
    JS软键盘代码
    JS判断RadioButtonList是否有选中项
    简单获取两个时间的时间差函数
  • 原文地址:https://www.cnblogs.com/sosoeasy/p/12746021.html
Copyright © 2011-2022 走看看