不抛出异常

时间:2016-09-24 07:54:42

标签: c# exception-handling

 try
{
    WebRequest request = WebRequest.Create("http://facebook.com");
    HttpWebResponse response = (HttpWebResponse) request.GetResponse();

    MessageBox.Show("I am here!");      // Not run                
}
catch (Exception ex)
{
    MessageBox.Show("Error Occurred!"); //Not run!
}

在我的国家/地区,Facebook已经过滤,当我运行此代码时,不会抛出异常,程序也不显示消息"我在这里!&#34 ;; 发生了什么?

我想每1分钟在timer_tick中使用此代码,并使用alive状态更新ui标签。你有其他方式吗?

1 个答案:

答案 0 :(得分:0)

我猜你的timer_tick()的间隔值小于w​​eb请求的默认超时值,然后在当前轮次完成之前执行下一个定时器轮次。因此为您的请求使用超时也最好使用Task在运行计时器时不冻结ui。

Task task = Task.Factory.StartNew(() =>
{
    WebRequest request = WebRequest.Create("http://facebook.com");
    request.Timeout = 5000;
    HttpWebResponse response = (HttpWebResponse) request.GetResponse();

});

// Run this code after successfully completing the task...
task.ContinueWith(t =>
{
   websiteIsAvailable = true;
   //Some code...
}, TaskContinuationOptions.OnlyOnRanToCompletion);

// Run this code after task Failure...
task.ContinueWith(t =>
{
   websiteIsAvailable = false;
   //Some code...
}, TaskContinuationOptions.OnlyOnFaulted);