Invoking UI thread from BeginGetResponse in Silverlight
I know how to do this in everyday .NET, but mucking rou开发者_StackOverflownd with WP7 development and Silverlight is driving me mad. An HttpWebRequest response must be done async, cool with that, but how can I invoke the UI thread from the async method?
i.e.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create('http://stackoverflow.com');
request.BeginGetResponse(new AsyncCallback(onRequestComplete), request);
I'm calling this in a class, which has a delegate set up. I'd like to call the delegate on the UI thread from onRequestComplete. I know I can do this the other way round, invoke from the delegate, but I feel this would be cleaner.
Thanks in advance
You need to have access to the relevant Dispatcher
, and then call Dispatcher.BeginInvoke
.
Any UI elements will have access to the system dispatcher via the Dispatcher
property. If you need to do this in a testable way, you may want to abstract out the dispatcher into an IDispatcher
interface with an implementation to use the normal one for production, and something like a SameThreadDispatcher
in tests.
精彩评论