views:

35

answers:

2

I have a WPF application which presents a list of items. 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).

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. I would like to do it asynchronously and update the UI after retrieving each piece of information. What is the best way to deal with this issue.

A: 

Hi,

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.

Some exemple here : http://msdn.microsoft.com/en-us/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

hope this help.

Xstahef
A: 

Use a BackgroundWorker to do the work. Update the UI in the ProgressChanged event handler

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;
}
Thomas Levesque
Thank you for your idea.Should there be a single BackgroundWorker? I am asking because I think it may be faster to get the results by having more than a single request to the web server at the same time.
GUZ
You can add a lot of BW in your app.Just think about to check their state (IsBusy) and check if form is not disable when you are on finished event.
Xstahef
Does each BW uses a new thread? I wonder because adding a BW per item may damage the performance if too many threads will be created.
GUZ
Yes, each BW uses a new thread. You could use multiple BWs, you just need to handle a queue of requests to process and dispatch them to the next available BW. Another option would be to use the ThreadPool class, however it's a bit harder to use, because you have to execute the code that accesses the UI on the UI thread, using invoke.
Thomas Levesque