请求超时处理c#winforms

时间:2013-11-10 23:36:36

标签: c# winforms

与其他WebException错误相比,我需要知道如何捕获并识别超时错误。 请求超时设置为“1”以使环境能够捕获异常。我只需要知道如何识别它。(即默认工作值= 60000)。这是我的代码:

// some code here
request.Timeout = 1;
// some code here

catch (WebException wex)
            {
                Console.WriteLine(wex);
                try
                {
                    response_code = ((int)((HttpWebResponse)wex.Response).StatusCode);
                    State_show.ForeColor = System.Drawing.Color.Red;
                    if (response_code == 404)
                    {
                        State_show.Text = "Error 404. Retrying the request";
                        request_1();
                    }
                    if (response_code != 400 || response_code != 503 || response_code != 404)
                    {
                        State_show.Text = "Error " + response_code + ". Please try again";
                        FlashWindow.Flash(this);
                    }
                }
                catch (Exception exc)
                {
                    Console.WriteLine(exc);
                    MessageBox.Show("Check internet connection");
                }
            }

因此,如果我收到错误的http状态代码,它会很好。但如果响应超时,它会抛出额外的异常。最简单的方法是获得

string wex_modified = wex.ToString();
If (wex_modified.contains("Timeout"))
{
      // some handling here
}

但我真的不喜欢它。我尝试使用wex.GetType()和其他可用函数,但没有成功。

还有其他方法可以识别异常吗?

1 个答案:

答案 0 :(得分:1)

WebException.Status property会返回WebExceptionStatus enum。其中一个枚举值为Timeout

if (wex.Status == WebExceptionStatus.Timeout)
{
   // We have a timeout!
}
相关问题