0

如何在每个连接执行之前检查连接是否仍然有效(也是全局 OnBeforeExecute 事件处理程序),或者我需要创建全局异常处理程序“从连接读取数据时出错”

4

1 回答 1

0

我发现最好的是您实际上必须尝试建立连接。

这是我存储的代码:

 private const int RETRY = 3;

 public bool Reachable(Uri Address, string responseExpected) {
   for (int i = 0; i < RETRY; i++) {
     try {
       WebRequest req = WebRequest.Create(Address);
       req.Method = "GET";
       using (WebResponse rsvp = req.GetResponse()) {
         using (Stream s = rsvp.GetResponseStream()) {
           using (StreamReader r = new StreamReader(s)) {
             string text = r.ReadToEnd();
             r.Close();
             if ((String.IsNullOrEmpty(responseExpected)) || (-1 < text.IndexOf(responseExpected))) {
               return true;
             }
           }
         }
       }
     } catch (Exception err) {
#if DEBUG
       Debug.WriteLine("Url: " + Address.ToString());
       Debug.WriteLine(err.Message);
#endif
     }
   }
   return false;
 }
于 2012-10-10T14:13:54.367 回答