HttpClient异步方法是否将在新线程中运行 [英] Will HttpClient Async methods run in new threads
问题描述
我想知道.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屋!