考虑以下:
private async void btnSlowPoke_Click(object sender, EventArgs e)
{
await DoItAsync();
}
private async Task<int> SomeLongJobAsync()
{
for (int x = 0; x < 999999; x++)
{
//ponder my existence for one second
await Task.Delay(1000);
}
return 42;
}
public async Task<int> DoItAsync()
{
Console.Write("She'll be coming round the mountain");
Task<int> t = SomeLongJobAsync(); //<--On what thread does this execute?
Console.WriteLine(" when she comes.");
return await t;
}
- 第一个写入
DoItAsync()
执行。
-
SomeLongJobAsync()
starts.
- The
WriteLine
in DoItAsync()
执行。
-
DoItAsync()
暂停同时SomeLongJobAsync()
一直工作直到完成。
-
SomeLongJobAsync()
完成,所以DoItAsync()
返回。
同时,用户界面具有响应能力。
在什么线程上SomeLongJobAsync()
执行?
简答
An async
方法由GUI
每当有CPU操作时,线程就会在同一个线程上执行to执行。其他async
方法开始在调用线程上运行并继续在ThreadPool
thread.
长答案
SomeLongJobAsync
开始在调用线程(打印的线程)上执行“她会绕山而来”)直到达到await
。然后返回一个任务,该任务代表异步操作+其后的延续。当。。。的时候entire操作完成后任务将完成(除非由于异常或取消而提前完成)。
When Task.Delay(1000)
本身就是“执行”没有线程,因为不需要。当最后Task.Delay(1000)
结束,一条线is需要继续。它是哪个线程取决于SynchronizationContext(默认情况下有none所以线程是ThreadPool
线程,但是在一个GUI
应用程序是单个 GUI 线程,更多here)。该线程执行其余的代码,直到到达另一个异步点(即另一个await
)等等。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)