Reputation: 122450
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?
Upvotes: 3
Views: 1750
Reputation: 3763
You can certainly update the UI using the Dispatcher.BeginInvoke method, to avoid cross-thread exceptions. It is however advisable to use HttpWebRequest instead of WebClient since WebClient returns on the UI thread. Here is a recent MSDN Blog post that could help you understand the model and perhaps aid in developing your app.
Upvotes: 0
Reputation: 11201
Yes, it does. Here is how you can expose asynchronous features to any type on WP7.
Upvotes: 0
Reputation: 14882
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
Upvotes: 3
Reputation: 10609
All network access in WP7 is asynchronous, most of the network api classes don't even expose synchronous methods, you have to fight the framework pretty hard to try in fact.
As noted in the other answers what you have to be aware of is that you need to update the UI through the UI thread, you can use Dispatcher.BeginInvoke if you're working with the code-behind. If you're using some sort of MVVM style pattern then INotifyPropertyChanged events are automatically dispatched back to the UI thread so you don't need to worry about it (INotifyCollectionChanged from ObservableCollection isn't for reasons unknown).
Upvotes: -1