async和await學習筆記

結論:異步

(1)asyc方法的返回類型必須爲:void、Task或者Task<T>。返回類型爲Task的異步方法中無需使用return返回值,而返回類型爲Task<TResult>的異步方法中必須使用return返回一個Tresult類型的值。async

(2)await必須用來修飾Task或Task<TResult>(方法和對象),且只能出如今已經用async關鍵字修飾的異步方法中。函數

(3)在async標識的方法體裏面,在await關鍵字出現以前,是由原線程順序調用的,運行到await處就會調整執行順序:await語句仍舊由原線程執行,直到遇到一個Task後新建一個線程執行Task任務。此時原線程將跳出async函數並執行其後代碼;await語句的下一條語句至async函數結束之間的語句會被掛起,由新建的Task線程在跳出await語句後繼續執行。await關鍵字本質上是是用於返回值是「可等待」類型(awaitable)的方法。spa

 

代碼:線程

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace TestConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("線程ID:" + Thread.CurrentThread.ManagedThreadId + "    -------主線程啓動-------");
            Task<int> task = OuterAsync();
            Thread.Sleep(1000);
            Console.WriteLine("線程ID:" + Thread.CurrentThread.ManagedThreadId + "    主線程繼續運行...");
            Console.WriteLine("線程ID:" + Thread.CurrentThread.ManagedThreadId + "    -------主線程結束-------");

            Console.ReadLine();
        }

        static async Task<int> OuterAsync()
        {
            Console.WriteLine("線程ID:" + Thread.CurrentThread.ManagedThreadId + "    OuterAsync() Start");

            string str = await TaskAsync();
            Console.WriteLine("線程ID:" + Thread.CurrentThread.ManagedThreadId + "    OuterAsync() End");
            return str.Length;
        }

        static Task<string> TaskAsync()
        {
            Console.WriteLine("線程ID:" + Thread.CurrentThread.ManagedThreadId + "    TaskAsync() Start");

            var result = Task<string>.Run(() =>
            {
                Thread.Sleep(2000);
                Console.WriteLine("線程ID:" + Thread.CurrentThread.ManagedThreadId + "    Task Running...");
                return "finished";
            });
            Console.WriteLine("線程ID:" + Thread.CurrentThread.ManagedThreadId + "    TaskAsync() End");
            return result;
        }
    }
}

 

分析:3d

相關文章
相關標籤/搜索