结论:
(1)asyc方法的返回类型必须为:void、Task或者Task<T>。返回类型为Task的异步方法中无需使用return返回值,而返回类型为Task<TResult>的异步方法中必须使用return返回一个Tresult类型的值。
(2)await必须用来修饰Task或Task<TResult>(方法和对象),且只能出现在已经用async关键字修饰的异步方法中。
(3)在async标识的方法体里面,在await关键字出现之前,是由原线程顺序调用的,运行到await处就会调整执行顺序:await语句仍旧由原线程执行,直到遇到一个Task后新建一个线程执行Task任务。此时原线程将跳出async函数并执行其后代码;await语句的下一条语句至async函数结束之间的语句会被挂起,由新建的Task线程在跳出await语句后继续执行。await关键字本质上是是用于返回值是“可等待”类型(awaitable)的方法。
代码:
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; } } }
分析: