capypad
0 day streak
csharp / expert
Snippet

Implementing Custom Awaiters

In C#, any type can be awaited if it follows the 'GetAwaiter' pattern. This expert-level technique allows you to create custom asynchronous primitives without relying on Task or ValueTask, reducing allocation overhead in specialized high-performance scenarios.

snippet.csharp
csharp
1
2
3
4
5
6
7
8
9
public struct MyTaskAwaiter : INotifyCompletion {
public bool IsCompleted => false;
public void OnCompleted(Action continuation) => Task.Run(continuation);
public void GetResult() { }
}
 
public struct MyCustomTask {
public MyTaskAwaiter GetAwaiter() => new MyTaskAwaiter();
}
Breakdown
1
public bool IsCompleted => false;
Determines if the operation is already finished; if false, the state machine yields.
2
public MyTaskAwaiter GetAwaiter()
The duck-typing method the compiler looks for to enable the 'await' keyword.