Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call external api from Web API synchronously

I need to call an external api from my Web API 2 controller, similar to the requirement here:

Calling external HTTP service using HttpClient from a Web API Action

However, the solution above requires adding the async keyword to my api method's GET call, thus making my call asynchronous. I prefer to present clients of my API with a synchronous method but still be able to call the external api from my own (and will need that to return before my api returns). Is there a way to do this?

like image 366
mayabelle Avatar asked Feb 16 '15 22:02

mayabelle


1 Answers

Blocking on an async operation could be dangerous. It hurts performance and could lead to deadlocks (more in Should I expose synchronous wrappers for asynchronous methods?)

But if you're sure that's what you want to do, It's better IMO to use GetAwaiter().GetResult():

using (HttpClient httpClient = new HttpClient())
{
    var response = httpClient.GetAsync(_endpoint).GetAwaiter().GetResult();
    var result = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
    // Do stuff...
}

It's the same whether it's a Task or Task<T>, it's the same call await translates to (although with await the task already completed) and Task.Result (or Task.Wait) wraps any exceptions in AggregateException while GetAwaiter().GetResult() throws only the first Exception as await does.

like image 151
i3arnon Avatar answered Nov 08 '22 01:11

i3arnon