问题
I'm using a WebClient
to get infos asynchronously from my web service :
wc.DownloadStringCompleted += DownloadStringCompleted;
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 !
回答1:
Use HttpWebRequest
rather than WebClient
. HWR doesn't return on the UI thread and so doesn't block it from updating.
回答2:
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 HttpWebReques
t 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
{
}
回答3:
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.
来源:https://stackoverflow.com/questions/4326937/silverlight-background-thread-using-webclient