【问题标题】:Retry on The operation has timed out or The connection was closed unexpectedly重试操作已超时或连接意外关闭
【发布时间】:2015-01-05 10:18:39
【问题描述】:

我只想重试那些失败且可能未到达目标服务器集的下载尝试。由于每次请求都会增加随机数,因此重试其他失败的尝试只会浪费时间。

这是我的简化下载方法,可能会像描述的那样工作:

public string Download(string url)
{
    bool retried = false;
    retry:
    try
    {
        HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
        using (StreamReader reader = new StreamReader(webrequest.GetResponse().GetResponseStream()))
        {
            return reader.ReadToEnd();
        }
    }
    catch (WebException e)
    {
        if (e.Message == "The operation has timed out" || e.Message == "The connection was closed unexpectedly")
        {
            if (!retried)
            {
                retried = true;
                goto retry;
            }
        }
    }
    return "";
}

问题是 e.Message 是本地化的。因此,我将不得不使用if (e.Message == "language 1" || e.Message == "language 2" || e.Message == "language 3" || ...)

有没有更优雅的方式只在The operation has timed outThe connection was closed unexpectedly 上重试?还是只重试可能尚未到达目标服务器的请求?谢谢!

【问题讨论】:

  • 我希望 WebException 对象的 HResultStatus 属性可以为您提供所需的信息。
  • 这看起来很有希望。我会测试它。感谢您的建议。

标签: c# timeout webrequest


【解决方案1】:

检查是否:

e.Status == WebExceptionStatus.Timeout || e.Status == WebExceptionStatus.KeepAliveFailure

你可以看到所有的 WebExceptionStatus 值here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-10
    • 2018-04-29
    • 2013-05-31
    • 1970-01-01
    相关资源
    最近更新 更多