DavidB
DavidB

Reputation: 2596

Await and Async usage

The MSDN documentation for await and async gives the following simple example.

async Task<int> AccessTheWebAsync()
{ 

    HttpClient client = new HttpClient();

    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

    DoIndependentWork();

    string urlContents = await getStringTask;

    return urlContents.Length;
}

It then states:

If AccessTheWebAsync doesn't have any work that it can do between calling GetStringAsync and awaiting its completion, you can simplify your code by calling and awaiting in the following single statement.

string urlContents = await client.GetStringAsync();

But if there is no work to be done between calling the method and its completion what are the benefits of making this method asynchronous?

Upvotes: 1

Views: 207

Answers (3)

gregkalapos
gregkalapos

Reputation: 3619

The await keyword means that the Thread starting the GetStringAsync method may become free during the execution of that method.

So for example let's say this is a web-server (e.g. with 10 threads in a thread-pool, which are responsible for processing the requests). In that case between the beginning of the GetStringAsync call and it's finish that thread is free to do other stuff.

Meaning even with 10 thread you can serve more then 10 users on a very effective way. If there would be no await in your code (and GetStringAsync would not be async, but a blocking synchronous method) and 11 users would access it at the same time then one of them would have trouble, since there would be no free thread to process the 11. request.

If that call would be a blocking synchronous code then the execution would just stay there and do nothing while your network card would just wait for the HTTP response from the server. So basically with "await" you avoid threads which are just waiting and do nothing.

Upvotes: 4

SKS
SKS

Reputation: 250

In general Async-Await consumes lesser threads, improves scalability by reducing memory/thread usage. It also improves responsiveness as compared to synchronous code.

check Advantages of Async-Await

Upvotes: 1

Hans Kesting
Hans Kesting

Reputation: 39338

When you await an async method, the thread is freed to do other work. In the synchronous version, that thread would have been blocked.

Upvotes: 3

Related Questions