I'm building a newsreader app for wp7. I'd like to have some background activity occur, like writing downloaded content to isolated storage. Is there any way to do this without blocking the UI thread?
The DownloadStringCompleted event of WebClient is asynchronous, right? Could I just do it there?
It is asynchronous, but it's recommended not to do any non trivial processing using WebClient since that work will be done on the UI thread as Indy rightly points out.
Webclient does this to offer you the convenience of not having to invoke the Dispatcher.
Dispatcher.BeginInvoke( () => { /* ui update code */ } );
This comes at the cost of ALL of your processing in the callback being executed on the UI thread.
HttpWebRequest (used by WebClient itself) will allow you to keep most your processing off the UI thread and just do your UI updates on the UI thread by way of the Dispatcher (refer above).
Note that you can still block the UI thread if you do this with too much intensity. Spacing your UI updates with Thread.Sleep(xxx) will help to keep the UI reponsive in such cases.
For a deeper understanding of the differences between HttpWebRequest and WebClient and a working project sample to demonstrate, refer my post here.
WebClient, HttpWebRequest and the UI Thread on Windows Phone 7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With