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/