简体   繁体   中英

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.

The problem is the code already in place use ManuelResetEvent to do web request synchronously. It works perfectly in WPF and Win 8 RT but in Windows Phone 8 (at least on emulator), the program hang as told here :

ManualResetEvent with HttpWebRequest on WP7

I tried both to encapsulate the call in a Task or Thread but it is still the same.

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. Sure, there is the Async Targeting Pack for Visual Studio 2012 but there is two problems with this :

  • 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)

So, I tried to call the async tagged methods synchronously, just to see. I used the AsyncHelpers given here :

How would I run an async Task<T> method synchronously?

It works on WPF and Win 8 apps, but it hangs on 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 ?

Maybe you cloud use the Result property of Task. It works on .NET 4.0/4.5 and Windows Phone 8.

The HttpWebRequest use UI thread to process a request, don't ask me why.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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