Observable.FromAsyncPattern 挂起 UI
最近,我决定使用 Windows Phone 7 的 Rx(反应式扩展),但遇到了一些奇怪的行为。
例如,我有这段代码:
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());
我试图弄清楚为什么当我到达 LINQ 查询时,它会挂起 UI 并且不会再进一步。有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
AFAIK,对 First 的调用是阻塞的,因此只有在收到响应后才会恢复执行。
尝试将其替换为
AFAIK, call to First is blocking, so execution will be resumed only after receiving response.
Try replace it with
关于这个场景,我将提出一件更重要的事情。正如已经指出的,First 确实是一个阻塞调用。为了解决使用 First() 时永远不会收到响应的评论,重要的是要在 Silverlight 中认识到,在接收网络数据时实际上使用了 UI 线程(Dispatcher)。因此,通过使用 First,您可以阻止 UI 线程接收 UI 线程正在等待的响应。在 Silverlight 中,切勿以任何原因阻塞 UI 线程,这一点至关重要。
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 关于
First()
阻塞的说法是正确的。在 Rx 中,你需要一直保持反应,否则你将不得不在某个地方阻塞。desco is correct about
First()
blocking. In Rx you need to stay reactive all the way down or you'll have to block somewhere.