【问题标题】:Loop,Try -> Catch Exception until it doesn't循环,尝试 -> 捕获异常,直到它没有
【发布时间】:2014-08-02 06:24:27
【问题描述】:

我有这个:

return request.GetResponse() as HttpWebResponse;

当网站不工作时它有时会抛出异常..(502错误)。

这个特定的网站只关闭了几秒钟..

所以.. 我需要创建一个循环并在上面尝试,然后捕获异常。

我试过这个:

while (true)
{
    try
    {
        return request.GetResponse() as HttpWebResponse;
        break; 
    }
    catch
    {

    }
}

但是,这给了我:Unreachable code detected on break.

【问题讨论】:

  • 返回充当休息,休息是不必要的
  • 使用这样的 catch 块也是一个坏主意。仅捕获您知道如何处理的特定异常。

标签: c# loops exception try-catch httpwebresponse


【解决方案1】:

所以..我去了这个:

while (true)
        {
            try
            {
                return request.GetResponse() as HttpWebResponse;
            }
            catch (Exception e)
            {
                if (e is WebException && allowedRetries-- > 0)
                {
                    System.Console.WriteLine("Trying to Reconnect...");
                    Thread.Sleep((int)millisecondsDelay);
                    //millisecondsDelay *= delayMultiplyFactor;
                }
                else
                {
                    throw;
                }
            }
        }

但它卡在“尝试重新连接...” 如果我重新启动它.. 它会立即连接。

整个功能..如果有帮助:

public static HttpWebResponse Request (string url, string method, NameValueCollection data = null, CookieContainer cookies = null, bool ajax = true)
    {
        HttpWebRequest request = WebRequest.Create (url) as HttpWebRequest;

        request.Method = method;

        request.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
        request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
        request.Host = "steamcommunity.com";
        request.UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11";
        request.Referer = "http://steamcommunity.com/trade/1";

        if (ajax)
        {
            request.Headers.Add ("X-Requested-With", "XMLHttpRequest");
            request.Headers.Add ("X-Prototype-Version", "1.7");
        }

        // Cookies
        request.CookieContainer = cookies ?? new CookieContainer ();

        // Request data
        if (data != null)
        {
            string dataString = String.Join ("&", Array.ConvertAll (data.AllKeys, key =>
                String.Format ("{0}={1}", HttpUtility.UrlEncode (key), HttpUtility.UrlEncode (data [key]))
            )
            );

            byte[] dataBytes = Encoding.ASCII.GetBytes (dataString);
            request.ContentLength = dataBytes.Length;

            Stream requestStream = request.GetRequestStream ();
            requestStream.Write (dataBytes, 0, dataBytes.Length);
        }

        // Get the response
        //return request.GetResponse () as HttpWebResponse;

        //EXCEPTION8712905

        double millisecondsDelay = 2000;//10
        //double delayMultiplyFactor = 2;
        int allowedRetries = 10000;//10

        while (true)
        {
            try
            {
                return request.GetResponse() as HttpWebResponse;
            }
            catch (Exception e)
            {
                if (e is WebException && allowedRetries-- > 0)
                {
                    System.Console.WriteLine("Trying to Reconnect...");
                    Thread.Sleep((int)millisecondsDelay);
                    //millisecondsDelay *= delayMultiplyFactor;
                }
                else
                {
                    throw;
                }
            }
        }
    }

【讨论】:

    【解决方案2】:

    正如其他人所提到的,break 是多余的;删除它可以消除您的警告。此外,您应该引入exponential backoff 以避免在可恢复故障的情况下占用您的系统(并用请求淹没服务器):

    double millisecondsDelay = 10;
    double delayMultiplyFactor = 2;
    int allowedRetries = 10;
    
    while (true)
    {
        try
        {
            return request.GetResponse() as HttpWebResponse;
        }
        catch (Exception e)
        {
            if (e is /* RecoverableException*/ && allowedRetries-- > 0)
            {
                Thread.Sleep((int)millisecondsDelay);
                millisecondsDelay *= delayMultiplyFactor;
            }
            else
            {
                throw;
            }
        }
    }
    

    【讨论】:

    • 太赫兹。 :) 让它整夜运行.. 因为要睡觉了。 :P 明天见。 :) 顺便说一句,我怎样才能添加所有 4 个可能的例外?只是为了确定.. :P -WebException -InvalidOperationException -NotSupportedException 和 -ProtocolViolationException
    • 是这样吗? if ((e is WebException || e is InvalidOperationException || e is NotSupportedException || e is ProtocolViolationException) && allowedRetries--> 0)
    • @user3712882:是的,尽管我建议将其重构为布尔方法。你也可以参考这个微软示例:msdn.microsoft.com/en-us/library/azure/dn448547.aspx
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 2021-12-13
    • 2011-12-05
    相关资源
    最近更新 更多