我正在尝试在await Thread.SleepAsync()
不创建任何额外线程的情况下实现自定义等待执行。
这是我所拥有的:
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();
}
}
}
以下是睡眠的工作原理:
static async Task Sleep(int milliseconds)
{
await new AwaitableThread(milliseconds);
}
OnCompleted
问题是这个函数立即返回,即使 inIsCompleted
仍然是假的。
我究竟做错了什么?