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);
            }
    

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

  • 相关阅读:
    js实现选择切换
    Jquery操作select
    Mybatis 高级结果映射 ResultMap Association Collection
    jQuery的一些特性和用法
    利用JSONP解决AJAX跨域问题的原理与jQuery解决方案
    List转成Array 连个Array比较
    3.15
    Get 和 Post 方法的选择和URL的设计
    fd
    如何维护一个1000 IP的免费代理池
  • 原文地址:https://www.cnblogs.com/qwfy-y/p/12597272.html
Copyright © 2011-2022 走看看