Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 728
Nghia Nguyen Avatar asked Jan 23 '26 11:01

Nghia Nguyen


2 Answers

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?

like image 187
Stephen Cleary Avatar answered Jan 25 '26 01:01

Stephen Cleary


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

like image 38
Toni Petrina Avatar answered Jan 24 '26 23:01

Toni Petrina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!