await Task.Delay() delaying for longer that expect

2019-05-06 05:34发布

问题:

I have a Windows Service application which uses .Net Tasks heavily. I have a decent understanding of them, but am no pro and am encountering a problem.

I have a situation where my await Task.Delay() takes much longer at times (up to 60 seconds longer) than it should. I'm sure this is due to something I'm doing, but I'm having trouble tracing it down what could influence this.

Here is a much simplified contrived example of the type of thing I'm doing.

public async Task DoDelay(CancellationToken token = default(CancellationToken))
{
    // Delay for then check to see if we need to extend our visibility timeout
    DateTime beforeDelay = DateTime.Now;

    // Wait for 180 seconds, i.e. 3 minutes
    await Task.Delay((int)180 * 1000, token).ConfigureAwait(false);

    // Check to see how long we actually delayed for
    TimeSpan durationOfDelay = DateTime.Now - beforeDelay;

    Trace.WriteLine("Duration: " + durationOfDelay.TotalSeconds.ToString());
}

Sometimes the durationOfDelay can be up to 60 seconds longer than I delayed for.

As some background, there might be multiple other Tasks calling DoDelay() and running at the same time. I've seen that at times, all of the awaited Task.Delay() calls finish at the same time despite having being awaited at different times with the same delay value.

For example:

// Non-awaited call executed at 00:00
DoDelay();

// Non-awaited call executed at 00:10
DoDelay();

// Non-awaited call executed at 00:20
DoDelay();

// Time goes by....
// Trace output:
// "Duration: 200"
// "Duration: 190"
// "Duration: 180"

What would cause this type of thing?