1. 程式人生 > 其它 >C# 中的Async 和 Await

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