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

本文关键字:意外 连接 操作 超时 重试 | 更新日期: 2023-09-27 18:29:38

我只想重试那些失败且可能未到达目标服务器集的下载尝试。重试其他失败的尝试也只是浪费时间,因为每次请求都会增加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.消息被本地化了。因此,我将不得不使用if (e.Message == "language 1" || e.Message == "language 2" || e.Message == "language 3" || ...)

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

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

检查是否:

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

您可以在此处查看所有WebExceptionStatus值