Sleep, delay, and cancellation — System Clock stack
The System Clock stack exposes synchronous Sleep and asynchronous DelayAsync APIs that route through the registered TimeProvider (so tests can substitute a virtual one). It also includes GetTimeCancellationToken to produce a TimeCancellationTokenSource that auto-cancels after a clock-driven elapsed time.
ServiceCollection services = [];
services.AddPrimeClock();
await using ServiceProvider serviceProvider = services.BuildServiceProvider();
IPrimeClock primeClock = serviceProvider.GetRequiredService<IPrimeClock>();
TimeSpan sleepDuration = _runMode == DemoRunMode.Long
? TimeSpan.FromSeconds(1)
: TimeSpan.FromMilliseconds(250);
TimeSpan delayDuration = _runMode == DemoRunMode.Long
? TimeSpan.FromSeconds(2)
: TimeSpan.FromSeconds(1);
TimeSpan cancellationAfter = _runMode == DemoRunMode.Long
? TimeSpan.FromSeconds(2)
: TimeSpan.FromMilliseconds(800);
ScenarioConsole.WriteLine($"Sleeping for {sleepDuration}...");
primeClock.Sleep(sleepDuration);
ScenarioConsole.WriteLine("Sleep completed.");
ScenarioConsole.WriteLine($"Running DelayAsync for {delayDuration}...");
await primeClock.DelayAsync(delayDuration, cancellationToken);
ScenarioConsole.WriteLine("DelayAsync completed.");
using TimeCancellationTokenSource timeout = primeClock.GetTimeCancellationToken(cancellationAfter);
try
{
ScenarioConsole.WriteLine($"Starting cancellable delay; timeout in {cancellationAfter}.");
await primeClock.DelayAsync(TimeSpan.FromSeconds(10), timeout.Token);
ScenarioConsole.WriteLine("Delay completed before timeout.");
}
catch (OperationCanceledException)
{
ScenarioConsole.WriteLine("Delay canceled by time-based cancellation token.");
}
What to notice
primeClock.Sleep(TimeSpan)blocks the calling thread for the specifiedTimeSpan. Under aPrimeTestClock, the call returns deterministically once virtual time is advanced.primeClock.DelayAsync(TimeSpan, CancellationToken)is the awaitable counterpart and honors the supplied cancellation token.GetTimeCancellationToken(TimeSpan)returns aTimeCancellationTokenSourcethat auto-cancels itsTokenafter the specified clock-time elapsed period — useful for awaitable timeouts that follow virtual time in tests.
Related
- Concepts: Timers, daylight saving, and testing
- API:
IPrimeClock·TimeCancellationTokenSource