using System.Diagnostics; namespace MyParking.Simulation.Core; /// /// 以固定周期推进离线仿真世界。 /// public sealed class SimulationClock( SimulationWorld world, ILogger logger) : BackgroundService { private static readonly TimeSpan TickInterval = TimeSpan.FromMilliseconds(20); protected override async Task ExecuteAsync( CancellationToken stoppingToken) { logger.LogInformation( "停车机器人离线仿真时钟已启动,周期{Period}ms。", TickInterval.TotalMilliseconds); using var timer = new PeriodicTimer(TickInterval); var stopwatch = Stopwatch.StartNew(); var previousSeconds = stopwatch.Elapsed.TotalSeconds; while (await timer.WaitForNextTickAsync(stoppingToken)) { var currentSeconds = stopwatch.Elapsed.TotalSeconds; var deltaTimeSeconds = Math.Clamp( currentSeconds - previousSeconds, 0.001, 0.1); previousSeconds = currentSeconds; world.Step(deltaTimeSeconds); } } }