Task.Delay 可以被告知延迟的最大持续时间是 int.MaxValue 毫秒。创建将延迟超过该时间的 Task 的最干净方法是什么?

// Fine.
await Task.Delay(TimeSpan.FromMilliseconds(int.MaxValue));

// ArgumentOutOfRangeException
await Task.Delay(TimeSpan.FromMilliseconds(int.MaxValue + 1L));

最佳答案

您无法使用单个 Task.Delay 来实现这一点,因为它在内部使用仅接受 int 的 System.Threading.Timer

但是,您可以一个接一个地使用多个等待来做到这一点。这是最干净的方法:

static async Task Delay(long delay)
{
    while (delay > 0)
    {
        var currentDelay = delay > int.MaxValue ? int.MaxValue : (int) delay;
        await Task.Delay(currentDelay);
        delay -= currentDelay;
    }
}

关于c# - Task.Delay 超过 int.MaxValue 毫秒,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27995221/

10-17 00:19