循环,尝试→捕捉异常,直到它没有't为止

本文关键字:为止 尝试 异常 循环 | 更新日期: 2023-09-27 18:08:27

我有这个:

return request.GetResponse() as HttpWebResponse;

和它有时抛出异常时,网站不工作。错误(502)。

这个特定的网站只会关闭几秒钟。

. .我需要创建一个循环并尝试上面的操作,并捕获异常。

我试过了:

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

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

循环,尝试→捕捉异常,直到它没有't为止

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

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

所以…我去了这个this:

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