2015-01-16 82 views
0

我的表單上有一個progressBar按鈕。 當用戶點擊這個按鈕時,progressBar應該被設置爲「marquee」並且程序開始檢查URL是否有效..好吧。如何在使用HttpWebRequest時防止UI凍結?

但是當我點擊該按鈕,用戶界面凍結,直到HttpStatusCode返回true或false ...

下面是校驗碼:

private bool RemoteFileExists(string url) 
{ 
    try 
    { 
     HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 
     request.Method = "HEAD"; 
     HttpWebResponse response = request.GetResponse() as HttpWebResponse; 
     return (response.StatusCode == HttpStatusCode.OK); 
    } 
    catch 
    { 
     return false; 
    } 
} 

這裏是按鈕,單擊代碼:

private async void button1_Click(object sender, EventArgs e) 
{ 
    this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Marquee; 
    var result = RemoteFileExists("http://www.google.com/"); 
    if (Completed) 
    { 
     //ok 
    } 
    else 
    { 
     //not ok 
    } 
} 
+0

檢查你應該使用異步方法: http://stackoverflow.com/questions/202481/how-to -use-httpwebrequest-net-asynchronously – Szer

+0

使用'HttpWebRequest.BeginGetResponse()'。看看這裏:http://stackoverflow.com/questions/202481/how-to-use-httpwebrequest-net-asynchronously – Icemanind

+0

http://msdn.microsoft.com/en-us/library/system.net.webrequest.getresponseasync (v = vs.110).aspx – Bharadwaj

回答

1

的UI凍結,因爲您正在執行的UI線程上RemoteFileExists方法和接收來自HttpWebRequest的響應需要一些時間。
要解決此問題,您必須在與UI線程不同的線程中執行RemoteFileExists
由於您的button1_Click方法已宣佈爲async,最簡單的方法是將RemoteFileExists也聲明爲async
然後您可以使用HttpWebRequest.GetResponseAsync方法異步接收響應對象。

private async Task<bool> RemoteFileExists(string url) 
{ 
    try 
    { 
     HttpWebRequest request = WebRequest.CreateHttp(url); 
     request.Method = "HEAD"; 

     using(var response = (HttpWebResponse) await request.GetResponseAsync()) 
     { 
      return (response.StatusCode == HttpStatusCode.OK); 
     } 
    } 
    catch 
    { 
     return false; 
    } 
} 

還與IDisposable小號打交道時,你應該考慮使用using聲明或調用Dispose()釋放所有使用的資源服務。
如果您使用的是.NET Framework 4+,則還可以使用WebRequest.CreateHttp(string)來創建您的HttpWebRequest

0

把它簡單的只是用這個:

private void button1_Click(object sender, EventArgs e) 
{ 
     this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Marquee; 
     Thread thread = new Thread(() => RemoteFileExists("http://www.google.com/")); 
     thread.IsBackground = true; 
     thread.SetApartmentState(ApartmentState.STA); 
     thread.Start(); 


} 

而且裏面做RemoteFileExists .