Question

Recently I decided to work with Rx (Reactive Extensions) for Windows Phone 7 and I encountered some weird behavior.

For example, I have this piece of code:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://whatismyip.org/");
request.Method = "GET";

var x = from c in Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse)()
            select c;

WebResponse r = x.First();
Debug.WriteLine(r.ContentType.ToString());

What I am trying to figure out is why when I reach the LINQ query, it hangs the UI and doesn't go any further than this. Any ideas?

Was it helpful?

Solution

AFAIK, call to First is blocking, so execution will be resumed only after receiving response. Try replace it with

x.Take(1).Subscribe(r => Debug.WriteLine(r.ContentType.ToString()));

OTHER TIPS

I'll throw in one more important thing about this scenario. As already noted, it is true that First is a blocking call. To address the comment that the response is never received when using First() though, it's important to realize in Silverlight that the UI thread (Dispatcher) is actually used when receiving the network data. So by using First, you block the UI thread from receiving the response the UI thread is waiting on. In Silverlight it is critical to never block the UI thread for any reason.

desco is correct about First() blocking. In Rx you need to stay reactive all the way down or you'll have to block somewhere.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top