async,await.task
Posted jinweichang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了async,await.task相关的知识,希望对你有一定的参考价值。
示例代码:
private void button16_Click(object sender, EventArgs e) { Console.WriteLine("按钮开始" + Thread.CurrentThread.ManagedThreadId.ToString()); task1(); Console.WriteLine("按钮结束" + Thread.CurrentThread.ManagedThreadId.ToString()); } static async Task task1() { Console.WriteLine("task1开始" + Thread.CurrentThread.ManagedThreadId.ToString()); Thread.Sleep(5); task2(); Console.WriteLine("task1结束" + Thread.CurrentThread.ManagedThreadId.ToString()); } static async Task<string> task2() { Console.WriteLine("task2开始" + Thread.CurrentThread.ManagedThreadId.ToString()); Thread.Sleep(5); await Task.Run(() => { Thread.Sleep(10); Console.WriteLine("xxxxxxxxxxxxxxxx" + Thread.CurrentThread.ManagedThreadId.ToString()); }); Console.WriteLine("task2结束" + Thread.CurrentThread.ManagedThreadId.ToString()); return "ddd"; }
async修饰的函数,在被调用时都会开个线程执行,如果加了await当前线程就会等待task2执行完后在往下执行,不加的话,就会并发一起执行。
以上是关于async,await.task的主要内容,如果未能解决你的问题,请参考以下文章
async await task.run xamarin 表单
为啥使用 IAsyncEnumerable 比返回 async/await Task<T> 慢?