是异步/等待使用Task.Run异步启动一个新的线程? [英] Is Async/Await using Task.Run starting a new thread asynchronously?
问题描述
我已经阅读了很多文章,仍然不能得到理解这一部分。
考虑这个code:
专用异步无效的button1_Click(对象发件人,EventArgs的发送)
{
等待DoSomething的();
} 私人异步任务<串GT;做一点事()
{
等待Task.Run((()=>中做工作));
回到我是完成;
}
第一个问题:
当我按一下按钮,它会调用DoSomething的,等待通过调用Task.Run创建从线程池线程(如果我没有记错),而这一切异步运行的任务。所以,我实现了创建一个线程,做我的工作,但异步干什么呢?但是考虑到我不需要任何结果回来了,我只是想工作,没有得到任何结果回来做,是真的有必要使用异步/在等待着,如果是这样,怎么样?
第二个问题:
在正在运行的线程异步,请问是怎么工作的?难道其上运行的主界面,但在一个单独的线程,或者它在一个单独的线程运行,分开是异步的方法内?我可能搞砸了异步方法和线程之间的区别,所以请裸跟我来。
- 创建异步方法是让你可以在以后等待他们的目的。有点像我打算把这个水烧开,完成prepping我汤料的休息,然后再回到锅内等待水煮沸结束,所以我可以做晚饭。你开始水沸腾,而你做其他的事情,它确实异步,但最终你必须停下来等待它。如果你想要的是射后不理,然后异步和等待是没有必要的。
<一个href=\"http://stackoverflow.com/questions/1018610/simplest-way-to-do-a-fire-and-forget-method-in-c\">Simplest这样做火,在C#中忘记方法是什么?
<醇开始=2>I have read a lot of articles and still cant get understand this part.
Consider this code :
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";
}
First question :
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 dont 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 ?
Second question :
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 seperate thread and separate is asynchronously inside that method? I may have messed up the difference between asynchronously methods and threads, so please bare with me.
- The purpose of creating Async methods is so you can Await them later. Kind of like "I'm going to put this water on to boil, finish prepping the rest of my soup ingredients, and then come back to the pot and wait for the water to finish boiling so I can make dinner." You start the water boiling, which it does asynchronously while you do other things, but eventually you have to stop and wait for it. If what you want is to "fire-and-forget" then Async and Await are not necessary.
Simplest way to do a fire and forget method in C#?
- Starting a new task queues that task for execution on a threadpool thread. Threads execute in the context of the process (eg. the executable that runs your application). If this is a web application running under IIS, then that thread is created in the context of the IIS worker process. That thread executes separately from the main execution thread, so it goes off and does its thing regardless of what your main execution thread is doing, and at the same time, your main execution thread moves on with its own work.
这篇关于是异步/等待使用Task.Run异步启动一个新的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!