Updating UI components from an async callback

心已入冬 提交于 2019-12-24 02:54:06

问题


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 exception, or confirm if my original assumption is correct?

Reference: http://www.silverlightshow.net/items/Tip-Asynchronous-Silverlight-Execute-on-the-UI-thread.aspx


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4072242/updating-ui-components-from-an-async-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!