希望有人可以帮我解决我的问题。Webclient DownloadString冻结主窗体
我尝试使用下面的代码来获得一个网站的HTML代码:
public string DownloadString(string add)
{
string html = "";
using (WebClient client = new WebClient())
{
client.Proxy = null;
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
while (html == "")
{
try
{
html = client.DownloadString(add);
}
catch (WebException e)
{
html = "";
}
}
client.Dispose();
}
return html;
}
我需要在字符串中的这个功能(来电):
public HtmlNode get_html(string add)
{
add_val(add);
Uri madd = new Uri(add);
Stopwatch timer = Stopwatch.StartNew();
Task<string> task = Task.Factory.StartNew<string>
(() => DownloadString(add));
string html = task.Result;
//string html = DownloadString(add);
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
//doc.Load(new StringReader(html));
doc.LoadHtml(html);
HtmlNode root = doc.DocumentNode;
timer.Stop();
TimeSpan timespan = timer.Elapsed;
label18.Text = String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds/10);
return root;
}
我曾尝试html = await client.DownloadStringTaskAsync(new Uri(add));
但它似乎没有工作,它仍然冻结用户界面,当我下载一个字符串。
预先感谢您!
可能重复的[如何使用WebClient而不阻止UI?](http://stackoverflow.com/questions/6118796/how-to-use-webclient-without-blocking-ui) – 2015-03-25 00:17:16
我试过了,它仍然冻结用户界面。 – NoobCS 2015-03-25 00:19:44
你仍然在你的用户界面的同一线程上运行...请使用** BackgroundWorker ** ..非常类似于**定时器** - 将授予您运行代码而不冻结的东西 – ymz 2015-03-25 00:39:41