1.概述
await/async:是个新语法,出现C#5.0,.NetFramework在4.5及以上(CLR4.0)是一个语法糖,不是一个全新的异步多线程使用方式.
语法糖:就是编译器提供的新功能
本身并不会产生新的线程,但是依托于Task而存在,所以程序执行时,也是有多线程的
async可以随便添加,可以不用await,但是await只能出现在task前面,但是方法必须声明async,不能单独出现
await/async之后,原本没有返回值的,可以返回Task,原本有返回值的,可以返回Task<TType>
2.基本用法
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace AsyncDemo1 { public class AwaitAsyncClass { public async Task DoSomething() { await Task.Run(()=> { Console.WriteLine("***********"); }); } } }
3.await关键字后执行顺序
(1)不加async和await的执行
public class AwaitAsyncClass { public void Show() { Console.WriteLine($"This Main Start {Thread.CurrentThread.ManagedThreadId} "); NoReturn(); Console.WriteLine($"This Main End {Thread.CurrentThread.ManagedThreadId} "); } public void NoReturn() { Console.WriteLine($"This NoReturn Start {Thread.CurrentThread.ManagedThreadId} "); Task.Run(()=> { Console.WriteLine($"This NoReturn Task Start {Thread.CurrentThread.ManagedThreadId} "); Thread.Sleep(2000); Console.WriteLine($"This NoReturn Task End {Thread.CurrentThread.ManagedThreadId} "); }); Console.WriteLine($"This NoReturn End {Thread.CurrentThread.ManagedThreadId} "); } }
static void Main(string[] args) { AwaitAsyncClass awaitAsync = new AwaitAsyncClass(); awaitAsync.Show(); Console.ReadLine(); }
执行结果:
(2)加上await后
public class AwaitAsyncClass { public void Show() { Console.WriteLine($"This Main Start {Thread.CurrentThread.ManagedThreadId} "); ReturnTask(); Console.WriteLine($"This Main End {Thread.CurrentThread.ManagedThreadId} "); } public async Task ReturnTask() { Console.WriteLine($"This NoReturn Start {Thread.CurrentThread.ManagedThreadId} ");//调用线程执行(主线程) Task task = Task.Run(()=> { Console.WriteLine($"This NoReturn Task Start {Thread.CurrentThread.ManagedThreadId} ");//Task的子线程完成 Thread.Sleep(2000); Console.WriteLine($"This NoReturn Task End {Thread.CurrentThread.ManagedThreadId} ");//Task的子线程完成 }); await task;//调用线程回去忙自己的事 Console.WriteLine($"This NoReturn End {Thread.CurrentThread.ManagedThreadId} ");//Task的子线程完成
} }
执行顺序:
(3) 加await的执行顺序,跟以下不加await的顺序一致
public void Show() { Console.WriteLine($"This Main Start {Thread.CurrentThread.ManagedThreadId} "); NoReturn(); Console.WriteLine($"This Main End {Thread.CurrentThread.ManagedThreadId} "); } public void NoReturn() { Console.WriteLine($"This NoReturn Start {Thread.CurrentThread.ManagedThreadId} "); Task task=Task.Run(() => { Console.WriteLine($"This NoReturn Task Start {Thread.CurrentThread.ManagedThreadId} "); Thread.Sleep(2000); Console.WriteLine($"This NoReturn Task End {Thread.CurrentThread.ManagedThreadId} "); }); //当task完成之后执行的回调动作 task.ContinueWith(t=> Console.WriteLine($"This NoReturn End {Thread.CurrentThread.ManagedThreadId} ")); }
总结:可以认为,加了await,就等同于将await后面的代码,包装成一个回调,其实回调的线程具备多种可能性
async await原理可以参考:https://www.cnblogs.com/heyuquan/archive/2012/11/30/async-and-await-faq.html