async/await create new thread, output window show that

一世执手 提交于 2020-02-04 01:33:13

问题


I read many articles said that async/await doesn't create additional threads. But the message from Output and Thread windows in debug mode of Visual Studio said the contrary.

I created a very simple example windows form with some code;

private void button2_Click(object sender, EventArgs e)
{
    Task t = methodAsync();
    //t.Wait();
}
async Task methodAsync()
{
    Console.WriteLine($"==before DownloadStringTaskAsync");
    using (var wc = new System.Net.WebClient())
    {
        string content = await wc.DownloadStringTaskAsync("https://stackoverflow.com");
    }
    Console.WriteLine($"==after DownloadStringTaskAsync");
}

I start app in debuging mode, I pause it by clicking pause button on Debug toolbar. Threads windows show there is only one Main thread, that's normal so far.

Then I click on button to execute methodAsync. When it complete DownloadString, I pause app again, and then I see serveral additional thread in Thread windows.

After about 10 seconds the Output windows shows message "The thread xxx has exited with code 0 (0x0)".

The same result when I replace WebClient.DownloadStringTaskAsync with await Task.Delay(xxx) I wonder if async/await does really create new thread or not.

Any explaination?


回答1:


async and await are just keywords that make a method awaitable, and then allow you to asynchronously wait for it and resume execution. Tasks are the underlying framework elements that represent the asynchronous result of the execution of the method, and the TaskScheduler is responsible for coordinating the execution of Tasks, which may involve using the Thread Pool, creating new threads, etc. The default Task Scheduler on Windows generally uses the Thread Pool to execute tasks.




回答2:


The WebClient.DownloadStringTaskAsync method uses Task-based Asynchronous Pattern and uses resource thread resources that are automatically allocated from the thread pool.

When you implement a TAP method, you can determine where asynchronous execution occurs. You may choose to execute the workload on the thread pool, implement it by using asynchronous I/O (without being bound to a thread for the majority of the operation’s execution), run it on a specific thread (such as the UI thread), or use any number of potential contexts.

As you can see in the method definition, it has an attribute ExternalThreading = true signalizing that it might allocate resources on external threads.



来源:https://stackoverflow.com/questions/48366871/async-await-create-new-thread-output-window-show-that

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!