2014-04-14 108 views
0

嗨大家即時通訊嘗試創建一個方法,將始終返回一個網址源,如果例如互聯網熄滅它將繼續工作,直到它出現並返回網址源等等,如果還有其他東西發生。到目前爲止在我的方法,當我「關閉」互聯網和「打開它」回程序繼續正常,但我有一個問題時發生超時,我在一個循環中「下降」我知道while(true)是不是正確的做法,但即時通訊用於我的測試。Webrequest不能「逃生」超時

那麼如何跳過超時異常並「重試」我的方法?

public static async Task<string> GetUrlSource(string url) 
{ 
    string source = ""; 
    while (true) 
    { 
     HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url); 
     hwr.AllowAutoRedirect = true; 
     hwr.UserAgent = UserAgent; 
     hwr.Headers.Add(hd_ac_lang[0], hd_ac_lang[1]); 
     hwr.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; 
     hwr.Timeout = 14000; 
     try 
     { 
      using (var response = hwr.GetResponse()) 
      { 
       using (var reader = new StreamReader(response.GetResponseStream())) 
       { 
        source = await reader.ReadToEndAsync(); 
        if (check_source(source)) 
        { 
         return source; 
        } 
       } 
      } 
     } 
     catch (WebException ex) 
     { 
      hwr.Abort(); 
      if (ex.Status == WebExceptionStatus.ProtocolError) 
      { 
       if (((HttpWebResponse)ex.Response).StatusCode == HttatusCode.NotFound) 
       { 
        // handle the 404 here 
        return "404"; 
       } 
       } 
       else 
       { 
       Console.WriteLine(ex.Status.ToString());  
       } 
     } 
    } 
} 

注:我曾經有hwr.Abort();成爲芬蘭條款,但它沒有幫助。

編輯:控制檯每14秒寫一次這條消息,因爲我的超時時間我認爲它與此相關。

+0

你目前的方法有什麼問題?你的超時會導致一個異常,並且你循環回來? – CathalMF

+0

@CathalMF我不知道,但第一次超時後,似乎是在一個循環。它就像之後的那樣永遠處於超時狀態。 – Incognito

+0

你確定它不是你的服務器端正在破壞導致超時循環嗎? – CathalMF

回答

1

的備選解決方案擺脫超時問題的可以是使用WebBrowser組分和導航到所需的URL(webbrowser1.Navigate(url);),並且直到documentcompleted事件引發在循環中等待,然後獲得源代碼由這條線:

string source = webbrowser1.DocumentText; 
+0

以及即時猜測這可以做的工作,但我想解決我的方法,並找到我的問題背後的原因。 – Incognito

0

好吧,似乎我找到了一個與請求的服務點相關的解決方案。

因此,在我發現超時發生時使用此來釋放連接。

hwr.ServicePoint.CloseConnectionGroup(hwr.ConnectionGroupName); 

我會保持更新。