C# 中的Async 和 Await

基本用法

 

注意 异步方法  必须要有 async 标记,内部 异步 对象 也要有 await 标记

 

static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            //callMethod();
            Method1();
            Console.WriteLine("=================");
            Console.ReadKey();
        }


public static async void Method1()
        {
            int count = 0;
          var t=   Task.Run(() =>   // 开始异步
            {
                //for (int i = 0; i < 100; i++)
                //{
                //    Thread.Sleep(10);
                //    Console.WriteLine(" Method 1");
                //    count += 1;
                //}
                count = 10;
                Console.WriteLine("Method1");
                return count;
            });
            await  t;  // 主线程继续,没有 await ,主线程会继续阻塞
            Thread.Sleep(5000);
            Console.WriteLine("end");
        }

  

posted @ 2021-09-08 09:55  zq爱生活爱代码  阅读(32)  评论(0编辑  收藏  举报