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
The main benefits of asynchronous programming using async / await include the following: Increase the performance and responsiveness of your application, particularly when you have long-running operations that do not require to block the execution.
They keyword async is used to make a function asynchronous. The await keyword will ask the execution to wait until the defined task gets executed. It allows the use of await Keyword inside the functions with async keyword. Using await in any other way will cause a syntax error.
The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.
Note: The purpose of async / await is to simplify the syntax necessary to consume promise-based APIs. The behavior of async / await is similar to combining generators and promises. Async functions always return a promise.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With