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
