liveBook · Manning

Task-based asynchronous pattern

As explained in Building Web APIs with ASP.NET Core

The Task-based Asynchronous Pattern is a .NET asynchronous programming pattern in which operations return tasks that represent eventual completion and optional results.

The Task-based Asynchronous Pattern (TAP) lets .NET web APIs start resource-intensive operations without blocking the calling thread. An operation returns a Task representing eventual completion and, optionally, a result; async and await coordinate continuation when that Task finishes. section 1.2.5 section 1.3

Apply TAP to an API operation by following these implementation steps:

  • Mark the action method async when it awaits a Task. section 1.2.5
  • Return Task or Task<TResult> instead of a direct result. section 1.2.5 section 5.2.1
  • Replace synchronous I/O methods with asynchronous counterparts, such as ToArrayAsync(), and await the result. section 5.2.1
  • Let the thread handle other incoming requests while the database or other resource-intensive operation completes. section 5.2.1

Asynchronous board-game retrieval

A BoardGameController can expose `public async Task<RestDTO<BoardGame[]>> Get()`, await `query.ToArrayAsync()`, and return the populated response. ASP.NET Core supports the async method transparently, so the controller becomes asynchronous without changing the API’s basic responsibility. 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"),
        }
    };
}

Inspect a complete controller example showing the async signature, Task<TResult> return type, awaited EF Core query, and response construction. section 5.2.1

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Demonstrates async, await, Task<TResult>, and ToArrayAsync(), but defers extensive asynchronous data-retrieval treatment.
Examples
Uses a sample Get action with Task.Run and a BoardGameController query using ToArrayAsync().
What it assumes
Assumes basic C# and ASP.NET Core controller knowledge while introducing Task return types and asynchronous EF Core methods.
What you can do after
Build asynchronous ASP.NET Core actions that await database operations without blocking request-handling threads.
How it connects
Connects async/await with ASP.NET Core, EF Core, database I/O, HTTP requests, and thread pools.

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.