重试操作已超时或连接意外关闭

时间:2014-11-08 19:43:53

标签: c# timeout webrequest

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

这是我的简化下载方法,可能会如下所述:

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重试?或者仅对可能尚未到达目标服务器的请求进行重试?谢谢!

1 个答案:

答案 0 :(得分:1)

检查是否:

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

您可以看到所有WebExceptionStatus值here