Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the benefit of using async to return data from database?

I've been reading a lot on WebApi2 and I really like it, however I just don't understand why every method is using async instead of standard methods.

Here is the example:

[ResponseType(typeof(BookDto))]
public async Task<IHttpActionResult> GetBook(int id)
{
    BookDto book = await db.Books.Include(b => b.Author)
        .Where(b => b.BookId == id)
        .Select(AsBookDto)
        .FirstOrDefaultAsync();
    if (book == null)
    {
        return NotFound();
    }

    return Ok(book);
}

What's the benefit here? I will still need to wait for my book to be loaded from db using ef before serving it. Does this somehow differs from regular way where I don't use tasks to retrieve book?

like image 317
Stan Avatar asked Sep 19 '13 16:09

Stan


1 Answers

On the server side (e.g., WebAPI), async methods allow the request thread to return to the thread pool while the database server is generating the response. This allows you to scale better.

When the database server returns the response to your WebAPI method (i.e., the task returned by FirstOrDefaultAsync completes), then ASP.NET will grab another thread from the thread pool and resume processing your request.

Note that not every method should be async. You should only use async when you want to await some operation. There's a great Channel9 video that describes the concepts and benefits of using async on ASP.NET. I also gave a talk at ThatConference this year on async on the server side (link to my blog post including slides).

like image 68
Stephen Cleary Avatar answered Oct 14 '22 08:10

Stephen Cleary