Why are Awaiters (async/await) structs and not cla

2019-04-22 03:13发布

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:

http://referencesource.microsoft.com/#mscorlib/system/runtime/compilerservices/TaskAwaiter.cs#b8626cdb2f1cbe65

public struct YieldAwaiter : ICriticalNotifyCompletion:

http://referencesource.microsoft.com/#mscorlib/system/runtime/compilerservices/YieldAwaitable.cs#1e1219f924e9e3b7

public struct TaskAwaiter<TResult> : ICriticalNotifyCompletion

http://referencesource.microsoft.com/#mscorlib/system/runtime/compilerservices/TaskAwaiter.cs#2c48fb3bdfc69022

1条回答
趁早两清
2楼-- · 2019-04-22 03:35

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 a class. To strengthen this statement, try compiling an async method in Roslyn in Debug mode, and you'll see the state-machine is a class, where-as compiling in Release will result in a struct. More on that in Why are async state machines classes (and not structs) in Roslyn?

查看更多
登录 后发表回答