Async/Await 是否使用 Task.Run 异步启动新线程? [英] Is Async/Await using Task.Run starting a new thread asynchronously?
问题描述
我看了很多文章,还是看不懂这部分.
I have read a lot of articles and still cant get understand this part.
考虑这个代码:
private async void button1_Click(object sender, EventArgs e)
{
await Dosomething();
}
private async Task<string> Dosomething()
{
await Task.Run((() => "Do Work"));
return "I am done";
}
第一个问题:
当我单击按钮时,它会调用 DoSomething 并等待一个通过调用 Task.Run(如果我没有记错的话)从线程池创建一个线程的任务,并且所有这些都是异步运行的.所以我实现了创建一个线程来完成我的工作但异步执行?但是考虑到我不需要返回任何结果,我只想在不返回任何结果的情况下完成工作,是否真的需要使用 async/await ,如果需要,如何使用?
When I click the button, it will Call DoSomething and await a Task that creates a Thread from the threadpool by calling Task.Run ( if I am not mistaken ) and all of this runs asynchronously. So I achieved creating a thread that does my work but doing it asynchronously? But consider that I don't need any result back, i just want the work to be done without getting any result back, is there really a need to use async/await , and if so, how?
第二个问题:
异步运行线程时,它是如何工作的?它是在主 UI 上运行但在单独的线程上运行,还是在单独的线程上运行并且单独在该方法内异步运行?
When running a thread asynchronously, how does that work? Is it running on the main UI but on a separate thread or is it running on a separate thread and separate is asynchronously inside that method?
推荐答案
- 创建异步方法的目的是让您可以稍后等待它们.有点像我要把这水烧开,准备好剩下的汤料,然后回到锅里,等水烧开,这样我就可以做晚饭了."你开始煮水,它在你做其他事情时异步进行,但最终你必须停下来等待它.如果您想要的是即发即忘",则不需要 Async 和 Await.
- 启动一个新任务会将该任务排队,以便在线程池线程上执行.线程在进程的上下文中执行(例如,运行您的应用程序的可执行文件).如果这是在 IIS 下运行的 Web 应用程序,则该线程是在 IIS 工作进程的上下文中创建的.该线程与主执行线程分开执行,因此无论您的主执行线程在做什么,它都会关闭并执行其任务,同时,您的主执行线程继续执行其自己的工作.
这篇关于Async/Await 是否使用 Task.Run 异步启动新线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!