File: TestServices\ObservingFakeTimeProvider.cs
Web Access
Project: src\tests\Aspire.Cli.Tests\Aspire.Cli.Tests.csproj (Aspire.Cli.Tests)
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
 
using Microsoft.Extensions.Time.Testing;
 
namespace Aspire.Cli.Tests.TestServices;
 
/// <summary>
/// A <see cref="FakeTimeProvider"/> that lets a test run code the next time the current time is read, for example to
/// change external state at the exact point where code under test starts polling on the clock.
/// </summary>
internal sealed class ObservingFakeTimeProvider : FakeTimeProvider
{
    private Action? _onNextUtcNowRead;
 
    /// <summary>
    /// Runs <paramref name="callback"/> once, on the next read of the current time and before that read returns.
    /// </summary>
    public void OnNextUtcNowRead(Action callback) => Volatile.Write(ref _onNextUtcNowRead, callback);
 
    public override DateTimeOffset GetUtcNow()
    {
        Interlocked.Exchange(ref _onNextUtcNowRead, null)?.Invoke();
        return base.GetUtcNow();
    }
}