当线程“唤醒"某物时会发生什么 [英] What happens to a thread when it 'awaits' something

查看:79
本文介绍了当线程“唤醒"某物时会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

async 方法唤醒一个 Task 方法时,它当前正在运行的线程会怎样?

When an async method awaits a Task what happens to the thread it's currently running on?

我猜想在UI线程上,消息循环会继续,而在线程池线程上,线程会释放回线程池.但是,如果手动启动线程会怎样?还有其他类型的线程吗?

I surmise that on a UI thread the message loop resumes and on a thread pool thread the thread is released back to the thread pool. But what happens if the thread was started manually? Are there any other types of threads?

推荐答案

这花了我很长时间才意识到,但是async-await的这一部分非常简单,只需向上调用栈即可.每当方法唤醒某些东西(假设它不是完成的Task或类似的东西)时,它都会返回给调用者.由于我们正在谈论的是代码让出线程控制权的那一点,这意味着这是代码顶部的最后一部分.

This took me a long time to realize but this part of async-await is dead simple, just go up the call stack. Any time a method awaits something (assuming it's not a completed Task or anything similar) it returns to the caller. Since we're talking about the point where your code cedes control of the thread that means this is the last piece of your code on top of the stack.

如果我们在U​​I线程上运行,我们将返回到消息循环.如果我们在线程池上,线程控制将返回到线程池.手动创建的线程仅运行void方法,如果它是 async void 方法,则只能使用 await ,这意味着它将在第一个 await ,甚至在方法完成之前.

If we're running on the UI thread we return back to the message loop. If we're on thread pool thread control returns to the thread pool. A manually created thread only runs a void method, you can only use await if it's an async void method which means it will end the thread at the first await even before the method has completed.

延续的工作方式相同.它将在UI线程或线程池上排队,然后再次唤醒或结束,再次将控制权让给

The continuations work the same way. It will queue it on either the UI thread or the thread pool, then it either awaits again or it finishes, ceding control once more.

我已经对自定义任务调度程序进行了一些试验,您可以在其中应用完全相同的逻辑.当任务等待时,它让出控制权.我使用的任务计划程序基于以下

I've done some experimenting with custom task schedulers and you can apply the exact same logic there. When the task awaits it cedes control. The task scheduler I used is based off this single threaded task scheduler. In this case ceding control means the task scheduler starts working on the next task in the queue. It's also important to note that the continuations are scheduled with the current task scheduler unless ConfigureAwait(false) is used.

这篇关于当线程“唤醒"某物时会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆