AlfredBr
AlfredBr

Reputation: 1351

If I'm going to use the result from await immediately, do I get any benefit from async?

Consider the code in this example:

https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

In several places they have code that looks like this:

if (response.IsSuccessStatusCode)
{
    product = await response.Content.ReadAsAsync<Product>();
}
return product;

The way I see it, if there is no independent code following the await, then there is little benefit to using async. (I know that there are many API's that are *AsAsync() only, so in those cases I don't have a choice.)

Or am I missing something? Is there a benefit for going all async, all the time?

Upvotes: 0

Views: 304

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

Yes there is benefit as we are not blocking caller on the operation that we are doing which is not the case for sync calls.

Think of it was called in windows form application as synchrounous call then on a button click suppose, then the app would be unresponsive and user wouldn't be able to do any operation until the call to Web API method complete s either with success or failure which we don't want nowadays in many cases I.e keep the application responsive for better UX.

The basic purpose is to simplify the old way of using background worker class to do long running operations or I/O bound operations. The asynchronous execution will cause not to block the caller code and resume from where it left when the result is returned back from the operation.

So in the above case calling a Web API method involves network latency and it could take more than normal time and if we are not calling it asynchronously we have blocked the calling code or thread until the result is returned.

Update:

To clarify Calling async method without await wouldnt block but your control would flow through and you won't be able to access the result while await would keep that context, without await you will have to wait for it to complete and block it like Async().Result which ofcoruse means calling async method synchronously.

Hope it helps

Upvotes: 4

Related Questions