Reputation: 562
I am trying to run a task based async method synchronously on WP. After reading the code from here. I succeed do that, call a async method from system library synchronously.
However, there is not task bases async method for each API, especially in WP, such as WebRequest.BeginGetResponse. So I wrote a wrap like:
Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse,
request.EndGetResponse, null);
And, what's ironic, when I try to call it synchronously from a UI thread (a little stange? I am just doing a test), my program is stuck in request.BeginGetResponse, and never go on.
But why? I use the same code to call a system api and my method. Is there any wrong in my code? or other something?
very thank for your help!
Upvotes: 0
Views: 1013
Reputation: 40235
You need to call Task.Start like this:
var requestTask = Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse,
request.EndGetResponse, null);
If you want it to be synchonous (I use that term lightly because it's not actually synchronous) you can then wait on the task.
Task.Wait(requestTask);
I would also recommend you think about adding the Async Nuget Package then you can async and await this task.
Upvotes: 1
Reputation: 456322
You're probably running into the deadlock situation I describe on my blog, where an async
method is attempting to resume on the UI thread while the UI thread is blocked.
The best solution is to use "async
all the way" - that is, change your synchronous calling method to be asynchronous.
Upvotes: 1