2011-03-24 50 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