RayLoveless
RayLoveless

Reputation: 21108

Why does HttpClient only allow for Async calls? c#

So apparently HttpClient only allows for Asnyc calls?

Of course you can call ".Result" like so:

public ActionResult Index()
{


            var someImportantData = httpClient.ReadAsStringAsync().Result;  // Aparently I shouldn't do this according to the article.
            // or    
            var someImportantData = Task.Run(() => Client.PostAsync()).Result;

            Return View( new MyViewModel(someImportantData));
}

to make it synchronous but this is apparently very dangerous and should be avoided because it causes deadlocking as described here.

So what are my options for Synchronous requests? I'm I going to be force to use the older HttpWebRequest? In my specific MVC action I want the call to be synchronous as I don't want to return the page until I collect data from a restful api call.

Upvotes: 4

Views: 578

Answers (2)

Nkosi
Nkosi

Reputation: 247531

If using async APIs then you should make your code async all the way. You can just as easily await the async members.

public async Task<ActionResult> Index() {
    var someImportantData = await httpClient.ReadAsStringAsync(...);
    return View(new MyViewModel(someImportantData));
}

I want my current thread to not proceed ( i.e: be synchronous ) and wait for the API call to return, then I can redirect to the new page.

The above call won't return the page until you collect data from the restful API call. Everything after the await will be back on the original thread.

.Result causes deadlocks as described in the article.

Yes. You sould avoid mixing async and blocking calls.

Upvotes: 3

Ankit Vijay
Ankit Vijay

Reputation: 4118

You do not really need to use .Result here. You can simply await for the result:

For example:

public async Task<ActionResult> Index()
{
      var someImportantData = await httpClient.ReadAsStringAsync().ConfigureAwait(false); 
      return View( new MyViewModel(someImportantData)); // This line will not be called until previous line is completed.
}

Use of ConfigureAwait(false) optional. If you are not using ASP.NET Core, then it can help a bit since you do not need to capture the context for server side code. Refer this link.

Upvotes: 0

Related Questions