Why are the awaiters (GetAwaiter - to make a class awaitable) structs and not classes. Does it harm to use a class?
public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion:
public struct YieldAwaiter : ICriticalNotifyCompletion:
public struct TaskAwaiter<TResult> : ICriticalNotifyCompletion
The reason behind making awaitables a struct is to avoid unnecessary heap allocations and minimize the memory footprint when the compiler creates the state machine behind the scenes.
This is an implementation detail. It is not necessary for an awaitable to be of type
struct
and not aclass
. To strengthen this statement, try compiling an async method in Roslyn inDebug
mode, and you'll see the state-machine is a class, where-as compiling inRelease
will result in astruct
. More on that in Why are async state machines classes (and not structs) in Roslyn?