Reputation: 10624
I'm confused about C# async. I understand async for parallel task processing. For example, a method does A and B task, and async enables A and B do action in the same time; B doesn't have to wait until A be done.
But the below example code does only a single task which is pulling data from a database. It means, there is nothing for parallel tasks. But why does it use async?
Please give me an advice so that I can understand async.
[ResponseType(typeof(BookDetailDTO))]
public async Task<IHttpActionResult> GetBook(int id)
{
var book = await db.Books.Include(b => b.Author).Select(b =>
new BookDetailDTO()
{
Id = b.Id,
Title = b.Title,
Year = b.Year,
Price = b.Price,
AuthorName = b.Author.Name,
Genre = b.Genre
}).SingleOrDefaultAsync(b => b.Id == id);
if (book == null)
{
return NotFound();
}
return Ok(book);
}
Upvotes: 2
Views: 246
Reputation: 456697
I explain this in detail in my async ASP.NET article. In summary, async
works by freeing up threads, so those threads can be used for other things.
means, there is nothing for parallel tasks. But why does it use async?
It's true that this request does not do multiple things concurrently; making it async does not speed up the request at all.
However, the application as a whole does have other things to do; specifically, it has other requests it can respond to. Using async
frees up thread pool threads whenever they're not being actively used. This allows your application to scale (assuming your backend is scalable). In other words, async
allows you to make maximum use of the thread pool.
Upvotes: 6
Reputation: 15
If you mark a function as async
and then call it using the await
-keyword at another point in your program, then the thread which called the async method doesn't block the execution of your program and can get suspended until it receives your answer.
That way i.e. your whole UI doesn't freeze up while you are pulling data from your database.
Upvotes: -3
Reputation: 137148
It uses aysnc because connecting to the database and getting a response could take some time and if it was done synchronously the application would be locked in a waiting state all that time.
By making the call asynchronous the application is free to do something else while the request is sent to the database and the data returned.
Upvotes: 0