4

我正在尝试在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仍然是假的。

我究竟做错了什么?

4

1 回答 1

10

完全实现用于生产的等待模式是一项棘手的工作——除其他外,您需要捕获执行上下文。Stephen Toub 关于这方面的博文有更多细节。在许多情况下,搭载Task<T>Task可能更容易使用TaskCompletionSource. 例如,在您的情况下,您可以编写如下等价物Task.Delay

public Task MyDelay(int milliseconds)
{
    // There's only a generic TaskCompletionSource, but we don't really
    // care about the result. Just use int as a reasonably cheap version.
    var tcs = new TaskCompletionSource<int>();

    Timer timer = new Timer(_ => tcs.SetResult(0), null, milliseconds,
                            Timeout.Infinite);
    // Capture the timer variable so that the timer can't be garbage collected
    // unless the task is (in which case it doesn't matter).
    tcs.Task.ContinueWith(task => timer = null);

    return tcs.Task;
}

您现在await可以执行该任务,就像您可以等待Task.Delay.

于 2012-11-17T13:15:00.670 回答