【发布时间】:2020-02-26 19:41:26
【问题描述】:
我正在使用 HttpClient 在 C# 应用程序 (.NET Framework 4.6.1) 中下载文件。
以下代码的问题是,如果在下载过程中连接断开,代码会卡在 CopyToAsync 方法。
如果我使用 WebClient.DownloadFileAsync 方法也会遇到同样的问题,但我想改用 HttpClient。
public class DownloadManager
{
private readonly HttpClientHandler _handler;
private readonly HttpClient _client;
public DownloadManager()
{
_handler = new HttpClientHandler();
_client = new HttpClient(_handler);
}
public async Task Download(string url, string file, CancellationToken cancellationToken)
{
try
{
var response = await _client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
if (response.IsSuccessStatusCode)
{
using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write))
{
var stream = await response.Content.ReadAsStreamAsync();
await stream.CopyToAsync(fileStream, 81920, cancellationToken);
}
}
}
catch (Exception ex)
{
if (cancellationToken.IsCancellationRequested)
{
throw new Exception("Download was cancelled");
}
throw ex;
}
}
}
【问题讨论】:
-
你设置timeout了吗?
-
是的,我设置了
_client.Timeout,但没有成功。根据文档,默认值为 100 秒。我认为这与流下载无关,而是与网络请求有关。
标签: c# .net download dotnet-httpclient