2010-02-27 39 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