HttpClient异步方法是否将在新线程中运行 [英] Will HttpClient Async methods run in new threads

查看:140
本文介绍了HttpClient异步方法是否将在新线程中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道.Net HttpClient async方法是在新线程中还是在主线程中运行.

I'm wondering whether .Net HttpClient async method run in new threads or in the main one.

例如,在控制台应用程序中,我调用async方法以使用HttpClient.GetStringAsync方法下载URL内容.

For example, In my Console Application, I invoke an async method to download a URL content using HttpClient.GetStringAsync method.

此方法(GetStringAsync)是否将在新的单独线程中运行?

Will this method (GetStringAsync) run in new separate thread?

推荐答案

通常,异步I/O方法不使用单独的线程.我会在我的博客文章没有线程.

In general, asynchronous I/O methods do not use separate threads. I explain this in detail in my blog post There Is No Thread.

但是,在这种情况下 并非如此. .NET中基于WebRequest的API长期以来一直支持异步操作,但实际上,即使通过它们的异步API,它们也总是像 synchronous 一样执行HTTP代理检测和DNS查找.当HttpClient开始流行时,便注意到了这一点.不幸的是,Microsoft决定来修复这些长期存在的错误.

However, in this specific case, that's not quite true. WebRequest-based APIs in .NET have supported asynchronous operations for a long time, but have actually always done HTTP proxy detection and DNS lookup as synchronous, even through their asynchronous APIs. This was noticed when HttpClient started becoming popular. Unfortunately, Microsoft decided not to fix these long-standing bugs.

因此,HttpClient将其WebRequest调用包装在线程池线程中.请注意,它仍在使用异步" API,因此仅同步部分(HTTP代理和DNS查找)在线程池线程上完成.请求的其余部分实际上是异步的.至少对于某些平台来说是这样.

So, HttpClient wraps its WebRequest calls in a thread pool thread. Note that it is still using the "asynchronous" APIs, so only the synchronous portion (HTTP proxy and DNS lookup) are done on a thread pool thread; the rest of the request is truly asynchronous. At least, this is true for some platforms.

这篇关于HttpClient异步方法是否将在新线程中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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