tgstation-server 6.12.0
The /tg/station 13 server suite
Loading...
Searching...
No Matches
AsyncDelayer.cs
Go to the documentation of this file.
1using System;
2using System.Diagnostics;
3using System.Threading;
4using System.Threading.Tasks;
5
6using Microsoft.Extensions.Logging;
7
9{
12 {
16 readonly ILogger<AsyncDelayer> logger;
17
22 public AsyncDelayer(ILogger<AsyncDelayer> logger)
23 {
24 this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
25 }
26
28 public async ValueTask Delay(TimeSpan timeSpan, CancellationToken cancellationToken)
29 {
30 // https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.delay?view=net-8.0#system-threading-tasks-task-delay(system-timespan)
31 const uint DelayMinutesLimit = UInt32.MaxValue - 1;
32 Debug.Assert(DelayMinutesLimit == 4294967294, "Delay limit assertion failure!");
33
34 var maxDelayIterations = 0UL;
35 if (timeSpan.TotalMilliseconds >= UInt32.MaxValue)
36 {
37 maxDelayIterations = (ulong)Math.Floor(timeSpan.TotalMilliseconds / DelayMinutesLimit);
38 logger.LogDebug("Breaking interval into {iterationCount} iterations", maxDelayIterations + 1);
39 timeSpan = TimeSpan.FromMilliseconds(timeSpan.TotalMilliseconds - (maxDelayIterations * DelayMinutesLimit));
40 }
41
42 if (maxDelayIterations > 0)
43 {
44 var longDelayTimeSpan = TimeSpan.FromMilliseconds(DelayMinutesLimit);
45 for (var i = 0UL; i < maxDelayIterations; ++i)
46 {
47 logger.LogTrace("Long delay #{iteration}...", i + 1);
48 await Task.Delay(longDelayTimeSpan, cancellationToken);
49 }
50
51 logger.LogTrace("Final delay iteration #{iteration}...", maxDelayIterations + 1);
52 }
53
54 await Task.Delay(timeSpan, cancellationToken);
55 }
56 }
57}
AsyncDelayer(ILogger< AsyncDelayer > logger)
Initializes a new instance of the AsyncDelayer class.
async ValueTask Delay(TimeSpan timeSpan, CancellationToken cancellationToken)
Create a Task that completes after a given timeSpan .A ValueTask representing the running operation.
readonly ILogger< AsyncDelayer > logger
The ILogger for the AsyncDelayer.