zoukankan      html  css  js  c++  java
  • C#Task中await和.Result和GetAwaiter().GetResult()方法的区别

    await不会阻塞调用它的线程,而GetAwaiter().GetResult()和.Result则会阻塞调用它的线程,但都会阻塞当前线程

            private  static  void Main()
            {
                Console.WriteLine("开始");
                test1();
                Console.WriteLine("第一个任务结束了");
                test2();
                Console.WriteLine("第二个任务结束了");
                test3Async();
                Console.WriteLine("第三个任务结束了");
                Console.ReadKey();
            }  
    
            public static void test1()
            {
                Console.WriteLine("第一个任务开始了");
                Task.Run(() =>
                {
                    Thread.Sleep(1000);
                    Console.WriteLine(1111);
                    
                }).GetAwaiter().GetResult();
                Console.WriteLine("第一个任务快完了");
                Thread.Sleep(2000);
            }
            public static async Task<bool> test2Async()
            {
                Console.WriteLine("第二个任务开始了");
                Thread.Sleep(1000);
                Console.WriteLine(2222);
                return true;
            }
    
            public static async Task test3Async()
            {
                Console.WriteLine("第三个任务开始了");
                await Task.Run(() =>
                {
                    Thread.Sleep(1000);
                    Console.WriteLine(3333);
                });
                Console.WriteLine("第三个任务快完了");
                Thread.Sleep(2000);
            }
            public static void test2()
            {
                var a = test2Async().Result;
                Console.WriteLine("第二个任务快完了");
                Thread.Sleep(2000);
            }
    

    如有错误,恳请指正!!!

  • 相关阅读:
    设置linux session 编码
    在masterpage中添加对usercontrol的引用
    首页的sitecontent地址
    iis的路径
    设置repeater每行多少个的方法
    updatepannel的使用
    取caml查询结果的前多少行
    设置视频自动播放
    网站集与网站
    notepad++ 死机 找到没保存的文件
  • 原文地址:https://www.cnblogs.com/qwfy-y/p/12597272.html
Copyright © 2011-2022 走看看