I am trying to implement a custom awaitable to execute await Thread.SleepAsync() without creating any additional threads.
Here is what I have:
class AwaitableThread : INotifyCompletion { public AwaitableThread(long milliseconds) { var timer = new Timer(obj => { IsCompleted = true; }, null, milliseconds, Timeout.Infinite); } private bool isCompleted = false; public bool IsCompleted { get { return isCompleted; } set { isCompleted = value; } } public void GetResult() {} public AwaitableThread GetAwaiter() { return this; } public void OnCompleted(Action continuation) { if (continuation != null) { continuation(); } } }
And this is how the dream will work:
static async Task Sleep(int milliseconds) { await new AwaitableThread(milliseconds); }
The problem is that this function returns immeasurably, although in OnCompleted , IsCompleted is still false.
What am I doing wrong?
source share