我有以下代码从网站获取数据
private void BeginCreationButton_Click(object sender, RoutedEventArgs e)
{
//Log("INFO", "Beggining ad creation");
GeneralProgressBar.Visibility = Visibility.Visible;
foreach(var ad in ads)
{
string adUh = string.Empty;
string errorMsg = string.Empty;
bool error = false;
//Task<string> uhFetch = Task<string>.Factory.StartNew(() => GetUhForAdvert());
Task task = Task.Factory.StartNew(() =>
{
HttpWebRequest newPromoRequest = WebRequest.Create("https://www.randomsite.com") as HttpWebRequest;
newPromoRequest.CookieContainer = Cookies;
newPromoRequest.Method = "GET";
newPromoRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
string uh = string.Empty;
HttpWebResponse response = (HttpWebResponse)newPromoRequest.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream s = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(s, Encoding.GetEncoding(response.CharacterSet)))
{
HtmlDocument doc = new HtmlDocument();
doc.Load(sr);
adUh = doc.DocumentNode.SelectNodes("//form")[0].SelectNodes("//input")[0].Attributes[2].Value;
}
}
}
});
try
{
task.Wait();
}
catch (AggregateException ae)
{
ae.Handle((x) =>
{
errorMsg = x.Message + " | " + x.StackTrace;
error = true;
return error;
});
}
if (error)
{
Log("ERROR", errorMsg);
}
Log("INFO", adUh);
}
}
然而,当任务正在执行时,UI被阻止但我不确定它为什么会发生。不确定它是流阅读还是HTML处理部分,因为我在没有这两个组件的项目的其他部分使用请求代码,它就像一个魅力。
答案 0 :(得分:3)
请勿使用task.Wait();
阻止您的UI线程。像这样按下按钮点击处理程序异步:
private async void BeginCreationButton_Click(object sender, RoutedEventArgs e)
{
// code here...
}
......以及你打电话的地方:
task.Wait();
......这样称呼:
await task;
此外,您不需要使用Task.Factory.StartNew
,只需使用(HttpWebResponse)await newPromoRequest.GetResponseAsync();
并将任务的所有代码包含在try catch
块中即可简化。
编辑:您可以阅读Stephen Cleary's blog了解有关此主题的详细说明。