Updating UI components from an async callback
Now I know about the Dispatcher and the DispatcherTimer and their benefits. But I've always been under the impression that an async web-service/WCF callback (completed event handler) are automatically handled by the UI thread.
But looking at some references online such as the one linked below, it seems this is NOT the case.
So the strange thing is that i haven't been using the Dispatcher to update the UI (updating data-bound ObservableCollections) within service completed events, yet I've never received a cross-thread exceptions.
Can anybody explain why i havent seen this except开发者_开发百科ion, or confirm if my original assumption is correct?
Reference: http://www.silverlightshow.net/items/Tip-Asynchronous-Silverlight-Execute-on-the-UI-thread.aspx
What the dispatcher do is putting a message into the normal windows message queuse. If you update an element bound to an UI element you don't need to use a dispatcher because the PropertyChanged raised when you update your model already put a message into the windows message queue, so you don't need to call any dispatcher, otherwise you just do two round trips into the window message queue.
The easiest explanation is it depends on how you are retrieving your data and whether you are trying to update the UI. For instance, when using HttpWebRequest directly it will always need to be marshaled back to the UI thread. However if you are using WebClient then that is done for you. WCF will also do some marshaling for you.
"WCF proxies in Silverlight applications use the SynchronizationContext of the thread from which the web service call is initiated to schedule the invocation of the async event handler when the response is received."
http://tomasz.janczuk.org/2009/08/improving-performance-of-concurrent-wcf.html
In other words, WCF will marshal the call back to the thread in which it was called from. So if you are invoking your service calls from the UI thread, then they will come back on the UI thread. If you are invoking your services on a different thread then you will need to do the marshaling yourself.
Hope that helps.
精彩评论