Observable.FromAsyncPattern 挂起 UI

发布于 2024-10-01 06:11:16 字数 480 浏览 5 评论 0原文

最近,我决定使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

生来就爱笑 2024-10-08 06:11:16

AFAIK,对 First 的调用是阻塞的,因此只有在收到响应后才会恢复执行。
尝试将其替换为

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

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()));
夜吻♂芭芘 2024-10-08 06:11:16

关于这个场景,我将提出一件更重要的事情。正如已经指出的,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.

小嗷兮 2024-10-08 06:11:16

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文