循环,尝试 - >捕获异常,直到它没有

时间:2014-06-12 02:50:56

标签: c# loops exception try-catch httpwebresponse

我有这个:

return request.GetResponse() as HttpWebResponse;

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

这个特定网站只会停机几秒钟。

所以..我需要做一个循环并尝试上面的内容,并捕获异常。

我试过了:

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

    }
}

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

2 个答案:

答案 0 :(得分: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;
        }
    }
}

答案 1 :(得分:0)

所以..我去了这个:

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;
                }
            }
        }
    }