async/await 的使用

async :
html

使用 async 修飾符可將方法、lambda 表達式匿名方法指定爲異步。 若是對方法或表達式使用此修飾符,則其稱爲異步方法express

await:編程

await 運算符應用於異步方法中的任務,在方法的執行中插入掛起點,直到所等待的任務完成,返回線程池任務表示正在進行的工做。多線程

 

 

 區別:異步

     同步方法:一個程序調用某個同步方法,等到其執行完成以後才進行下一步操做。這也是默認的形式。
     異步方法:一個程序調用某個異步方法(建立線程 【線程池】),取處理完成以前就返回該方法,並繼續往下執行其餘代碼。

 

 

 執行流程:async

異步用例:ide

只有擁有async才能在其內部使用await關鍵字。異步方法能夠具備Task、Task<>或void的返回類型;異步編程

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("主線程測試開始..");
            AsyncMethod();
            Thread.Sleep(1000);
            Console.WriteLine("主線程測試結束..");
            Console.ReadLine();
        }

        static async void AsyncMethod()
        {
            Console.WriteLine("開始異步代碼");
            var result = await MyMethod();//var result = MyMethod().Result
            Console.WriteLine("異步代碼執行完畢");
        }

        static async Task<int> MyMethod()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("異步執行" + i.ToString() + "..");
                await Task.Delay(1000); //模擬耗時操做
            }
            return 0;
        }
    }

 

Thread多線程異步編程例子:測試

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("主線程測試開始..");
            Thread th = new Thread(ThMethod);
            th.Start();
            Thread.Sleep(1000);
            Console.WriteLine("主線程測試結束..");
            Console.ReadLine();
        }
     
     
        static void ThMethod()
        {
            Console.WriteLine("異步執行開始");
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("異步執行" + i.ToString() + "..");
                Thread.Sleep(1000);
            }
            Console.WriteLine("異步執行完成");
        }
    }


 

 

 

參考:   http://www.javashuo.com/article/p-pxxfsemu-q.html   //線程池傳送門ui

    http://www.javashuo.com/article/p-tqcehmav-w.html

    http://www.javashuo.com/article/p-rivobvpq-bz.html

    https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/async/

    http://www.javashuo.com/article/p-glgzatop-kc.html

相關文章
相關標籤/搜索