简体   繁体   English

在Windows Phone 8上同步HttpWebRequest

[英]HttpWebRequest synchronous on Windows Phone 8

In order to design / reuse a library usable both for WPF apps, Windows Phone 8 apps and later Windows 8 / RT apps, we need to make some HttpWebRequest call, preferably synchronously not to break existing apps. 为了设计/重用可用于WPF应用程序,Windows Phone 8应用程序和更高版本的Windows 8 / RT应用程序的库,我们需要进行一些HttpWebRequest调用,最好同步进行以不破坏现有应用程序。

The problem is the code already in place use ManuelResetEvent to do web request synchronously. 问题是代码已经就绪,可以使用ManuelResetEvent同步执行Web请求。 It works perfectly in WPF and Win 8 RT but in Windows Phone 8 (at least on emulator), the program hang as told here : 它可以在WPF和Win 8 RT中完美运行,但是在Windows Phone 8中(至少在模拟器上),程序会如下所示挂起:

ManualResetEvent with HttpWebRequest on WP7 WP7上带有HttpWebRequest的ManualResetEvent

I tried both to encapsulate the call in a Task or Thread but it is still the same. 我都尝试将调用封装在Task或Thread中,但仍然相同。

So, I changed the code to use async / await and it will of course be perfect for WP8 & Win 8 but our desktop app is targeting .NET 4.0 framework for XP compatibility. 因此,我更改了代码以使用async / await,它对于WP8和Win 8当然是完美的选择,但我们的桌面应用程序的目标是.NET 4.0框架以实现XP兼容性。 Sure, there is the Async Targeting Pack for Visual Studio 2012 but there is two problems with this : 当然,有适用于Visual Studio 2012的异步定位包,但这有两个问题:

  • The desktop app code should be rewritten / carefully tested with async / await 桌面应用代码应使用异步/等待方式重写/仔细测试
  • Stable release of Mono does not support async / await (perhaps compîling with the Async Targeting Pack on Windows then running it on Mono runtime could work ? Should be tested) Mono的稳定版本不支持异步/等待(也许与Windows上的Async Targeting Pack兼容,然后可以在Mono运行时上运行它,应该进行测试?)

So, I tried to call the async tagged methods synchronously, just to see. 因此,我尝试同步调用异步标记的方法,以了解情况。 I used the AsyncHelpers given here : 我使用了此处给出的AsyncHelpers:

How would I run an async Task<T> method synchronously? 如何同步运行异步Task <T>方法?

It works on WPF and Win 8 apps, but it hangs on Windows Phone 8. 它可以在WPF和Win 8应用程序上运行,但可以挂在Windows Phone 8上。

Does someone know how to have a synchronous code (or synchronous looking code with await / async) that could be used everywhere without hanging on Windows Phone ? 有人知道如何拥有一个同步代码(或带有await / async的同步查找代码),该代码可以在任何地方使用而无需挂在Windows Phone上吗?

Maybe you cloud use the Result property of Task. 也许您可以使用Task的Result属性进行云计算。 It works on .NET 4.0/4.5 and Windows Phone 8. 它适用于.NET 4.0 / 4.5和Windows Phone 8。

The HttpWebRequest use UI thread to process a request, don't ask me why. HttpWebRequest使用UI线程来处理请求,不要问我为什么。

So if you try to wait a result by lock the UI thread, you will get a deadlock condition, because you lock UI thread until request is not complete and request will not be complete while UI thread is locked. 因此,如果您尝试通过锁定UI线程来等待结果,则会遇到死锁条件,因为您将UI线程锁定到请求未完成且UI线程被锁定时请求也不会完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM