希望有人可以幫我解決我的問題。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