简体   繁体   English

从Internet异步收集信息

[英]Harvesting information from the Internet asynchronously

I have a WPF application which presents a list of items. 我有一个WPF应用程序,其中显示了项目列表。 I would like to show an icon in UI if certain information exists on a web server for a given item (I need to download HTML web-page and verify its content to decide if the icon should be shown or not). 如果某个给定项目的Web服务器上存在某些信息,我想在UI中显示一个图标(我需要下载HTML网页并验证其内容,以确定是否应该显示该图标)。

The number of items may be quite big (more than 100), so requesting a web server synchronously may freeze the application for a longer time. 项目数量可能非常大(超过100个),因此同步请求Web服务器可能会使应用程序冻结更长的时间。 I would like to do it asynchronously and update the UI after retrieving each piece of information. 我想异步执行此操作,并在检索每条信息后更新UI。 What is the best way to deal with this issue. 解决此问题的最佳方法是什么。

Using Backgroundworkers is a good way to solve your problem It's easy to use : You run an asyn operation without freeze your app and you are notified when operation asyn is done. 使用Backgroundworkers是解决问题的好方法。它很容易使用:您可以运行ayn操作而不冻结应用程序,并且在完成asyn操作时会收到通知。

Some exemple here : http://msdn.microsoft.com/en-us/magazine/cc163328.aspx http://channel9.msdn.com/forums/TechOff/252416-C-and-WPF-progressbar/ 此处的一些示例: http : //msdn.microsoft.com/zh-cn/magazine/cc163328.aspx http://channel9.msdn.com/forums/TechOff/252416-C-and-WPF-progressbar/

MSDN definition of BW : http://msdn.microsoft.com/en-us/library/8xs8549b.aspx BW的MSDN定义: http : //msdn.microsoft.com/zh-cn/library/8xs8549b.aspx

hope this help. 希望有帮助。

Use a BackgroundWorker to do the work. 使用BackgroundWorker进行工作。 Update the UI in the ProgressChanged event handler 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM