async/await创建新线程,输出窗口显示 [英] async/await create new thread, output window show that

查看:79
本文介绍了async/await创建新线程,输出窗口显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过许多文章说,异步/等待不会创建其他线程.但是在Visual Studio的调试模式下,来自输出"和线程"窗口的消息却相反.

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.

我用一些代码创建了一个非常简单的示例Windows窗体;

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.

然后单击按钮以执行 methodAsync .当它完成DownloadString时,我再次暂停应用程序,然后在线程"窗口中看到服务器附加线程.

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.

大约10秒钟后,输出窗口将显示消息线程xxx已退出,代码为0(0x0)" .

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

当我用 await Task.Delay(xxx)替换 WebClient.DownloadStringTaskAsync 时,结果相同我想知道async/await是否确实创建了新线程.

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.

有什么解释吗?

推荐答案

async await 只是构成方法任务是基础表示方法执行异步结果的框架元素,以及

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.

这篇关于async/await创建新线程,输出窗口显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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