简体   繁体   中英

Async-Await vs Task<T>.Result on WP8

 var factory1 = new TaskFactory();
 var task1 =  factory1.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null).Result;

The above code work on windows 8 and windows store but when I try to run it in windows phone 8, it doesn't work. It just freeze and doesn't response anything, look like it take forever to run the task.

My purpose is to call web service synchronous, without using asycn and await method.

My purpose is to call web service synchronous, without using asycn and await method.

You're not supposed to do that. WP8/Win8 are supposed to be asynchronous. async and await make asynchronous programming easy.

I have a blog post that explains the Result deadlock situation in detail (though I'm a bit surprised it happens in this scenario). In short, the async method is attempting to resume on the UI thread but the UI thread is blocked waiting for the async method to complete.

Why do you want it synchronous?

This is supposed to happen. When you request Result, the application will stop and wait until you actually get the result. This means you wait synchronously.

If you want to wait asynchronously, you must use await keyword since the semantics for it are: when you get the result, then continue with the execution; in the meantime, carry on with UI work .

That is the difference between wait (implied synchrony) and asynchronous wait (aka await).

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