C# async await的使用
async 声明一个包含异步代码的函数,该函数执行时不会阻塞调用线程。
async标记的函数返回值必须为 void ,Task,Task<TResult>
await 必须修饰Task 或者Task<TResult>
await之后的代码运行线程:对于纯console工程,还是耗时任务的线程,
对于winform线程,则是调用线程。
典型代码
public static async Task<int> CalAsync() { string tid = Thread.CurrentThread.ManagedThreadId.ToString(); Console.WriteLine("当前位置async函数,await之前,线程ID"+tid); int result = await Task.Run(new Func<int>(Cal)); tid = Thread.CurrentThread.ManagedThreadId.ToString(); Console.WriteLine("当前位置async函数,await之后,线程ID" + tid); return result; }
全部代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { string tid = Thread.CurrentThread.ManagedThreadId.ToString(); Console.WriteLine("当前位置主函数,调用async异步之前,线程ID"+tid); Task<int> t = CalAsync(); Console.WriteLine("当前位置主函数,调用async异步之后,线程ID" + tid); Console.Read(); } public static async Task<int> CalAsync() { string tid = Thread.CurrentThread.ManagedThreadId.ToString(); Console.WriteLine("当前位置async函数,await之前,线程ID"+tid); int result = await Task.Run(new Func<int>(Cal)); tid = Thread.CurrentThread.ManagedThreadId.ToString(); Console.WriteLine("当前位置async函数,await之后,线程ID" + tid); return result; } public static int Cal() { string tid = Thread.CurrentThread.ManagedThreadId.ToString(); Console.WriteLine("当前位置耗时函数,线程ID"+tid); int sum = 0; for (int i = 0; i < 999; i++) { sum = sum + i; } Console.WriteLine("当前位置耗时函数完成,线程ID" + tid); return sum; } }
输入内容
winform中优雅的实现
private async void button1_Click(object sender, EventArgs e) { var t = Task.Run(() => { Thread.Sleep(5000); return "Returning from TimeConsuming task"; }); this.Text = await t; }
参考