开发者

Silverlight Background Thread using WebClient

I'm using a WebClient to get infos asynchronously from my web service :

    wc.DownloadStringCompleted += DownloadString开发者_开发百科Completed;
    wc.DownloadStringAsync(service);

I works fine, but I think the DownloadStringCompleted method is working on the UI Thread, and since i'm doing a lot of parsing there, my page takes a few seconds to appear. However, since I have so fixed data and a progress bar, I would'nt mind have it appearing instantly.

How could I perfom this ?

Thanks !


Use HttpWebRequest rather than WebClient. HWR doesn't return on the UI thread and so doesn't block it from updating.


WebClient does indeed return on the UI thread so yes your parsing will be blocking the UI. For perf reasons it is recommended that you use HttpWebRequest instead.

With HttpWebRequest your event will fire on the background thread so you can do all the processing you need, however you then have the problem of marshaling the results back to the UI thread so that you can update the UI (otherwise you will see cross thread violation exceptions). You can use the Dispatcher to marshal the results back to the UI with a method like the following:

private void UpdateUI(Results results)
{
    if (!Deployment.Current.Dispatcher.CheckAccess())
        Deployment.Current.Dispatcher.BeginInvoke(() => UpdateUI(results));
    else
    {
        //Update the UI
    {
}


In Mango the WebClient is changed so that if the

wc.DownloadStringAsync(service);

call is made from the background thread the response also comes to the background thread. You can use the BackgroundWorker to achieve this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜