簡體   English   中英

服務器關閉時C#應用程序崩潰

[英]c# application is crashing when the server is down

我正在使用以下代碼,以在* Form1_Load *中獲取我的應用程序的最新版本:

string result1 = null;
string url1 = "http://site.com/version.html";
WebResponse response1 = null;
StreamReader reader1 = null;

try
{
   HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(url1);
   request1.Method = "GET";
   response1 = request1.GetResponse();
   reader1 = new StreamReader(response1.GetResponseStream(), Encoding.UTF8);
   result1 = reader1.ReadToEnd();
 }
 catch (Exception ex)
 {
   // show the error if any.                
 }
 finally
 {
    if (reader1 != null)
         reader1.Close();
    if (response1 != null)
         response1.Close();
 }

問題是,當我關閉服務器時,整個應用程序都停滯了,並且彈出了一個窗口,說:

無法連接到遠程服務器

這似乎合法。

有沒有辦法避免崩潰(當服務器關閉時)並突破版本檢查?

添加一個額外的catch塊來捕獲您所看到的特定Exception類型...代碼將如下所示...

try
{
//*yadda yadda yadda*
}
catch (System.Net.WebException WebEx)
{
//*Correctly set up a situation where the rest of your program will know there was a connection problem to the website.*
}
catch (Exception ex)
{
//*Do the error catching you do now*
}
finally
{
//*yadda yadda*
}

這種構造將使您可以不同於其他類型的異常來處理WebException:請注意,所有Exception都派生自一個基類Exception,並且您可以像這樣使用自己的異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM