![](/img/trans.png)
[英]Retrieve information from a REST service asynchronously while throttling the number of requests
[英]Harvesting information from the Internet asynchronously
我有一个WPF应用程序,其中显示了项目列表。 如果某个给定项目的Web服务器上存在某些信息,我想在UI中显示一个图标(我需要下载HTML网页并验证其内容,以确定是否应该显示该图标)。
项目数量可能非常大(超过100个),因此同步请求Web服务器可能会使应用程序冻结更长的时间。 我想异步执行此操作,并在检索每条信息后更新UI。 解决此问题的最佳方法是什么。
使用Backgroundworkers是解决问题的好方法。它很容易使用:您可以运行ayn操作而不冻结应用程序,并且在完成asyn操作时会收到通知。
此处的一些示例: http : //msdn.microsoft.com/zh-cn/magazine/cc163328.aspx http://channel9.msdn.com/forums/TechOff/252416-C-and-WPF-progressbar/
BW的MSDN定义: http : //msdn.microsoft.com/zh-cn/library/8xs8549b.aspx
希望有帮助。
使用BackgroundWorker
进行工作。 在ProgressChanged
事件处理程序中更新UI
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
WebClient wc = new WebClient();
int count = urlsToCheck.Count;
for(int i = 0; i < count; i++)
{
bool urlValid = CheckUrl(url);
backgroundWorker1.ReportProgress(100 * (i + 1) / count, new CheckUrlResult(url, urlValid));
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
CheckUrlResult result = e.UserState as CheckUrlResult;
textBox1.Text += string.Format("{0} : {1}\n", result.Url, result.IsValid);
progressBar1.Value = e.ProgressPercentage;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.