Chapter 6. The Task-Based Asynchronous Pattern
The Task-based Asynchronous Pattern (TAP) is a set of recommendations
from Microsoft for writing
asynchronous APIs in .NET using Task
. The
document
by Stephen Toub from the parallel programming team at Microsoft has good
examples and is worth a read.
The pattern makes APIs that can be consumed using await
, and while using async
produces methods that follow the pattern,
it’s often useful to use Task
manually.
In this chapter, I’ll explain the pattern, and techniques to work with
it.
What the TAP Specifies
I’ll assume we already know how to design a good method signature for synchronous C# code:
It should have a few parameters, or maybe none.
ref
andout
parameters should be avoided if possible.It should have a return type, if it makes sense, which really expresses the result of the code inside the method, as opposed to a success indicator like in some C++ code.
It should have a name that explains the behavior of the method, without extra notation.
Common or expected failures should be part of the return type, while unexpected failures should throw exceptions.
Here is a well designed synchronous method, which is part of the
Dns
class:
public
static
IPHostEntry
GetHostEntry
(
string
hostNameOrAddress
)
The TAP gives the same level of guidelines on designing an asynchronous method, based on your existing skills with synchronous methods. Here they are:
It should have the same parameters as an equivalent synchronous method would.
ref
andout
parameters ...
Get Async in C# 5.0 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.