我正在学习c#并尝试了我在stackoverflow上找到的其他解决方案..但我失败了..
我在点击按钮时尝试检查网址是否存在。
单击该按钮时,progressBar将设置为选取框并开始验证。
但系统会停止,直到结果退回..
这是按钮点击:
private void button1_Click(object sender, EventArgs e)
{
this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Marquee;
if (RemoteFileExists("http://www.gofdisodfi.com/"))
{
// OK
}
else
{
//FAIL
}
}
这是支票:
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;
}
}
答案 0 :(得分:1)
您可以使用" async并等待"异步操作的语法。它不会冻结UI
private async void button1_Click(object sender, EventArgs e)
{
this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Marquee;
var result = await RemoteFileExists("http://www.google.com/");
if (result)
{
// OK
MessageBox.Show("OK");
}
else
{
//FAIL
MessageBox.Show("Fail");
}
}
private async Task<bool> RemoteFileExists(string url)
{
try
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
return false;
}
}
您可以在此处详细了解:http://blog.stephencleary.com/2012/02/async-and-await.html