每个 HTTP 请求都必须处理 Windows.Web.Http.HttpClient 吗?
Do Windows.Web.Http.HttpClient have to be disposed per HTTP request?
从这个 answer to the question: 中,我发现最佳做法是 而不是 为每个 HTTP 请求配置一个 System.Net.Http.HttpClient
。特别声明:
standard usage of HttpClient is not to dispose of it after every request.
那很好。
我的问题是,这个 "pattern" 是否也适用于 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…
[强调我的]
要使对象充当 "a collection of settings that apply to all requests executed by that instance",显然它必须用于多个请求。
从这个 answer to the question: 中,我发现最佳做法是 而不是 为每个 HTTP 请求配置一个 System.Net.Http.HttpClient
。特别声明:
standard usage of HttpClient is not to dispose of it after every request.
那很好。
我的问题是,这个 "pattern" 是否也适用于 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…
[强调我的]
要使对象充当 "a collection of settings that apply to all requests executed by that instance",显然它必须用于多个请求。