我的表單上有一個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
}
}
檢查你應該使用異步方法: http://stackoverflow.com/questions/202481/how-to -use-httpwebrequest-net-asynchronously – Szer
使用'HttpWebRequest.BeginGetResponse()'。看看這裏:http://stackoverflow.com/questions/202481/how-to-use-httpwebrequest-net-asynchronously – Icemanind
http://msdn.microsoft.com/en-us/library/system.net.webrequest.getresponseasync (v = vs.110).aspx – Bharadwaj