2010-02-27 48 views
4

我使用此代码片段验证URL中指定的文件是否存在,并且每隔几秒为每个用户持续尝试一次。有时(大多数情况下,当有大量用户使用该站点时)代码不起作用。.NET中的WebRequest异常

[WebMethod()] 
    public static string GetStatus(string URL) 
    { 
     bool completed = false; 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); 

     using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
     { 
      try 
      { 
       if (response.StatusCode == HttpStatusCode.OK) 
       { 
        completed = true; 
       } 
      } 
      catch (Exception) 
      { 
       //Just don't do anything. Retry after few seconds 
      } 
     } 

     return completed.ToString(); 
    } 

当我看到Windows事件日志存在几个误区:

Unable to read data from the transport connection. An existing connection was forcibly closed 

The Operation has timed out 

The remote host closed the connection. The error code is 0x800703E3 

当我重新启动IIS,一切工作正常,下一次出现这种情况,直到。

回答

4

你把try/catch语句的using语句中,而它可能抛出的request.GetResponse方法:

bool completed = false; 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); 
try 
{ 
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
    { 
     if (response.StatusCode == HttpStatusCode.OK) 
     { 
      completed = true; 
     } 
    } 
} 
catch (Exception) 
{ 
    //Just don't do anything. Retry after few seconds 
} 
return completed.ToString(); 
+0

你能解释一下你为什么此异常被抛出的想法?我的确了解了需要设置为false的KeepAlive属性,但我不确定在这种情况下是否需要这样做。 – DotnetDude 2010-02-27 15:22:50

+1

当HTTP请求超时时,可能发生的情况太多。 – 2010-02-27 15:26:19

+1

理论上,当一个HTTP请求超时时,我会认为它会简单地关闭连接。我不确定为什么其他用户在一个连接超时后立即受到影响。 – DotnetDude 2010-02-27 15:34:10