考虑以下几点:
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()
中的第一个 Write。 SomeLongJobAsync()
开始。DoItAsync()
中的WriteLine
执行。DoItAsync()
暂停,而SomeLongJobAsync()
一直工作直到完成。SomeLongJobAsync()
完成,因此DoItAsync()
返回。
同时,UI 是响应式的。
SomeLongJobAsync()
在什么线程上执行?
最佳答案
简答
GUI
线程触发的async
方法将在同一线程上执行,只要有 CPU 操作 执行。其他 async
方法开始在调用线程上运行,并在 ThreadPool
线程上继续运行。
长答案
SomeLongJobAsync
开始在调用线程(打印“She'll be coming round the mountain”)上执行,直到它到达 await
。然后返回一个任务,代表异步操作+它之后的延续。当整个操作完成时,任务将完成(除非由于异常或取消而提前完成)。
当 Task.Delay(1000)
本身正在“执行”时 there is no thread ,因为不需要。当最终 Task.Delay(1000)
结束时,需要一个线程 来恢复。它是哪个线程取决于 SynchronizationContext
(默认情况下没有 none,所以线程是 ThreadPool
线程,但在 GUI
应用程序中它是单个 GUI 线程,更多 here ).该线程执行其余代码,直到它到达另一个异步点(即另一个 await
)等等。
关于c# - 'awaited'任务在哪里执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24441101/