2011-03-24 26 views
0

有時候服務器關機,服務器上的文件丟失等問題。所以,我想在使用Dispatcher線程更新UI上的內容時捕獲或捕獲由HttpWebRequest引發的異常。如何獲得HttpWebrequest爲Wp7引發的異常/錯誤

下面的代碼無法捕獲錯誤並顯示在MessageBox.show()中。任何人都可以告訴我我需要做什麼?謝謝

HttpWebRequest webReq; 
    HttpWebResponse webResp; 

    public void GetInfo(string Url) 
    { 
     webReq = (HttpWebRequest)HttpWebRequest.Create(Url); 

     try 
     { 
      webReq.BeginGetResponse(OnGetBuffer, this); 
     } 
     catch (Exception e) 
     { 

     } 
    } 

    public void OnGetBuffer(IAsyncResult asr) 
    { 
     webResp = (HttpWebResponse)webReq.EndGetResponse(asr); 

     Deployment.Current.Dispatcher.BeginInvoke(() => 
     { 
      Stream streamResult = webResp.GetResponseStream(); 

      try 
      { 

      } 
      catch (Exception) 
      { 

      } 
     }); 
    } 
+1

@Richard施奈德我希望更多的人意識到了這一點 – harryovers 2011-03-24 00:48:33

回答

1

圍繞.EndGetResponse()調用放一個try/catch。我相信這是拋出異常的地方。

+0

感謝。已經嘗試過這一點,並沒有工作 – MilkBottle 2011-03-24 00:42:50

0

嘗試使用WebClient對象。然後在完成的事件處理程序中,錯誤返回爲e.Error

+0

謝謝。知道這個,但我需要使用HttpWebRequest。 – MilkBottle 2011-03-24 00:39:25

1

首先,我希望您不打算捕獲所有異常並全部忽略它們。你會忽略與你的網絡連接失敗無關的異常。

其次,你需要放置的try/catch周圍可能拋出異常的代碼:

public void OnGetBuffer(IAsyncResult asr) 
{ 
    HttpWebResponse webResp; 
    try 
    { 
     webResp = (HttpWebResponse)webReq.EndGetResponse(asr); 
    } 
    Catch (WebException ex) 
    { 
     // Do something to decide whether to retry, then retry or else 
     throw; // Re-throw if you're not going to handle the exception 
    } 

    Deployment.Current.Dispatcher.BeginInvoke(() => 
    { 
     using (Stream streamResult = webResp.GetResponseStream()) 
     { 
      // Do something with the stream 
     } 
    }); 
} 
+0

我嘗試過所有可能的場景中嘗試語句的所有組合。沒有可以做的。看起來調度員鎖定了線程。我會放棄這種方法並嘗試其他方式。無論如何,謝謝。 – MilkBottle 2011-04-15 10:09:08

相關問題