If you want to do some advanced stuff with async/await in C# I can recommend the AsyncUtilities library from Bar Arnon. It contains a set of useful utilities and extensions for async programming.
From the documentation:
I especially like the support for TaskEnumerableAwaiter and the nice way he implemented it using the fact that when implementing async/await the compiler doesn’t expect Task
or Task<T>
specifically, it looks for a GetAwaiter
method that returns an awaiter that in turn implements INotifyCompletion
and has:
IsCompleted
: Enables optimizations when the operation completes synchronously.OnCompleted
: Accepts the callback to invoke when the asynchronous operation completes.GetResult
: Returns the result of the operation (if there is one) and rethrows the exception if one occurred.
Thanks to the fact that GetAwaiter
can also be an extension method it becomes possible to turn existing types to awaitables with the right custom awaiter.
Bar did exactly that for awaiting a collection of tasks:
More information: http://blog.i3arnon.com/2018/01/02/task-enumerable-awaiter/