如何为大文件正确配置 HttpClient 的流?
How to correctly configure HttpClient's streaming for large files?
Microsoft 的 HttpClient 官方文档指出,如果我们想使用 HttpClient 下载大文件,我们应该
stream those downloads and not use the default buffering. If the default buffering is used the client memory usage will get very large, potentially resulting in substantially reduced performance.
什么是默认缓冲,我们如何更改它,以便无论我们最终下载的文件大小如何,我们都不会遇到上面概述的问题?
非常感谢提供虚拟代码片段!
你必须使用GetStreamAsync
方法。如 documentation 中所述:
This operation will not block. The returned Task object will complete after the response headers are read. This method does not read nor buffer the response body.
示例:
HttpClient httpClient = new HttpClient();
var requestUri = "http://url-to-resource.com";
var stream = await httpClient.GetStreamAsync(requestUri);
using (var fileStream = File.Create("outputFile.ext"))
{
await stream.CopyToAsync(fileStream);
}
所有其他方法如 GetByteArrayAsync
或 GetStringAsync
将缓冲响应并在读取整个响应正文后完成。
CopyToAsync
使用的默认缓冲区大小是 _DefaultCopyBufferSize 声明的 81920 字节。您可以使用重载 CopyToAsync(Stream, Int32)
.
来更改它
Microsoft 的 HttpClient 官方文档指出,如果我们想使用 HttpClient 下载大文件,我们应该
stream those downloads and not use the default buffering. If the default buffering is used the client memory usage will get very large, potentially resulting in substantially reduced performance.
什么是默认缓冲,我们如何更改它,以便无论我们最终下载的文件大小如何,我们都不会遇到上面概述的问题?
非常感谢提供虚拟代码片段!
你必须使用GetStreamAsync
方法。如 documentation 中所述:
This operation will not block. The returned Task object will complete after the response headers are read. This method does not read nor buffer the response body.
示例:
HttpClient httpClient = new HttpClient();
var requestUri = "http://url-to-resource.com";
var stream = await httpClient.GetStreamAsync(requestUri);
using (var fileStream = File.Create("outputFile.ext"))
{
await stream.CopyToAsync(fileStream);
}
所有其他方法如 GetByteArrayAsync
或 GetStringAsync
将缓冲响应并在读取整个响应正文后完成。
CopyToAsync
使用的默认缓冲区大小是 _DefaultCopyBufferSize 声明的 81920 字节。您可以使用重载 CopyToAsync(Stream, Int32)
.