【问题标题】:HttpClient download stuck if connection drops如果连接断开,HttpClient 下载会卡住
【发布时间】: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


【解决方案1】:

您必须在从HttpClient 获得的Stream 上设置ReadTimeout 属性。 ReadTimeout 默认设置为 300_000(5 分钟)。

using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write))
{
    var stream = await response.Content.ReadAsStreamAsync();
    // stream.CanTimeout -> this returns true
    stream.ReadTimeout = 1000; // ReadTimeout takes number of milliseconds
    await stream.CopyToAsync(fileStream, 81920, cancellationToken);
}

这仅适用于 .NET Framework。 stream.CanTimeout 属性在 .NET Core 上返回 false

【讨论】:

  • 我已设置ReadTimeout,但问题仍然存在。 ReadTimeout 会影响CopyToAsync 方法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-22
相关资源
最近更新 更多