c# - 是否必须根据 HTTP 请求处理 Windows.Web.Http.HttpClient?

标签 c# .net windows-store-apps dotnet-httpclient

<分区>

从这里answer问题:Do HttpClient and HttpClientHandler have to be disposed? ,我发现最佳做法是为每个 HTTP 请求处理 System.Net.Http.HttpClient。特别声明:

standard usage of HttpClient is not to dispose of it after every request.

那很好。

我的问题是,这种“模式”是否也适用于 Windows.Web.Http.HttpClient?还是应该根据 HTTP 请求处理它?我认为 documentation对此有点含糊。在其中一个示例中,它只是说明:

// Once your app is done using the HttpClient object call dispose to 
// free up system resources (the underlying socket and memory used for the object)
httpclient.Dispose();

我相信这可以从两个方面来理解,因此欢迎任何关于此的具体输入。

最佳答案

在我看来,如果它打算一次只用于一个请求,那么如果您尝试将它用于多个请求,它只会抛出一个异常。

另外,考虑到除了最早版本的 HTTP 之外,所有的 HTTP 都允许对给定的 TCP 连接进行多个请求。使用相同的 HttpClient 对象允许框架为多个请求维护 TCP 连接。

虽然示例代码确实只执行一个请求,但请注意 the documentation 中的这段文字:

The HttpClient class instance acts as a session to send HTTP requests and receive responses. An HttpClient instance is a collection of settings that apply to all requests executed by that instance. In addition, every HttpClient instance uses its own connection pool…

[强调我的]

对于充当“适用于该实例执行的所有请求的一组设置”的对象,显然它必须用于多个请求。

关于c# - 是否必须根据 HTTP 请求处理 Windows.Web.Http.HttpClient?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31295441/

相关文章:

xaml - 访问文本 block 的背景色

c# - 通过迁移动态创建数据库

c# - 如何将 Unicode 字符转换为其等效的 ASCII 字符

c# - Entity Framework 无法与 MySql 一起使用

c# - 在 XAML 中显示格式化文本

windows-8 - AllowAllTrustedApps 注册表项在 Windows RT 中不可用

c# - 线程的奇怪地方?

c# - SignalR Core 未在 Azure App Service 中使用 Websockets

c# - 关于圆周率计算程序的问题

.net - 如何从 IObservable<A> 转换为 IObservable<B>