views:

49

answers:

1

Hi guys

I know how to do this in everyday .NET, but mucking round 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

+1  A: 

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.

Jon Skeet
Thanks. So next question - where has InvokeRequired gone? Google says to use CheckAccess but I can't see that.
Sam
@Sam: CheckAccess *should* be there. It's documented. In my experience though, you generally know whether or not you're going to have to invoke via the dispatcher - and if you're not sure, it's almost always safe to do so anyway.
Jon Skeet
@Jon - Thanks. Yeah, for some reason it doesn't come up in IntelliSense in VS2010, but yeah, I tried it after my last comment and it works. Thanks.
Sam
It's there, just Intellisense doesn't show it.
Mick N