liveBook · Manning

Async/await

As explained in Building Web APIs with ASP.NET Core

The await operator asynchronously waits for a task to complete without blocking the executing thread.

async/await lets an ASP.NET Core action wait for work without blocking its calling thread. async marks a method that returns a Task, while await resumes execution when that Task completes. section 1.2.5

Apply the pattern when a board-game API performs work such as database I/O:

  • Mark the controller action async. section 5.2.1
  • Return Task<TResult> instead of the synchronous result type. section 5.2.1
  • Replace synchronous I/O methods such as ToArray() with asynchronous counterparts such as ToArrayAsync(). section 5.2.1
  • Await the operation so the thread can handle other incoming calls while the result is pending. section 5.2.1

Board-game query

A controller can return Task<RestDTO<BoardGame[]>> and assign Data = await query.ToArrayAsync(). ASP.NET Core handles the asynchronous action transparently. section 5.2.1

public async Task<RestDTO<BoardGame[]>> Get()
{
    var query = _context.BoardGames;
 
    return new RestDTO<BoardGame[]>()
    {
        Data = await query.ToArrayAsync(),
        Links = new List<LinkDTO> {
            new LinkDTO(
                Url.Action(null, "BoardGames", null, Request.Scheme)!,
                "self",
                "GET"),
        }
    };
}

Browse the complete asynchronous BoardGame query, including its Task return type, awaited EF Core query, and response links. section 5.2.1

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Walks through method signatures and EF Core replacements, while deferring extensive asynchronous data retrieval to later treatment.
Examples
Uses a placeholder Task.Run action and an awaited BoardGame ToArrayAsync database query.
What it assumes
Assumes basic C#, ASP.NET Core actions, and EF Core queries while showing the required async signatures from the action level.
What you can do after
Apply async/await by converting controller actions and replacing synchronous EF Core I/O methods with asynchronous counterparts.
How it connects
Connects async/await with the Task-based Asynchronous Pattern, ASP.NET Core, EF Core, and database I/O.

Also explained in

Compare how 17 books explain async/await →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.