servicepoint-tanks/TanksServer/GameTickWorker.cs

57 lines
1.5 KiB
C#
Raw Normal View History

2024-04-07 20:29:09 +02:00
using System.Diagnostics;
2024-04-06 21:15:26 +02:00
using Microsoft.Extensions.Hosting;
2024-04-07 20:16:22 +02:00
using Microsoft.Extensions.Logging;
2024-04-07 19:52:16 +02:00
using TanksServer.TickSteps;
2024-04-06 21:15:26 +02:00
2024-04-07 20:29:09 +02:00
namespace TanksServer;
2024-04-06 21:15:26 +02:00
2024-04-07 20:29:09 +02:00
internal sealed class GameTickWorker(
IEnumerable<ITickStep> steps, IHostApplicationLifetime lifetime, ILogger<GameTickWorker> logger
2024-04-07 20:16:22 +02:00
) : IHostedService, IDisposable
2024-04-06 21:15:26 +02:00
{
private readonly CancellationTokenSource _cancellation = new();
private readonly List<ITickStep> _steps = steps.ToList();
private Task? _run;
public Task StartAsync(CancellationToken cancellationToken)
{
_run = RunAsync();
return Task.CompletedTask;
}
private async Task RunAsync()
{
2024-04-07 20:16:22 +02:00
try
2024-04-06 21:15:26 +02:00
{
2024-04-07 20:29:09 +02:00
var sw = new Stopwatch();
2024-04-07 20:16:22 +02:00
while (!_cancellation.IsCancellationRequested)
{
2024-04-07 20:29:09 +02:00
logger.LogTrace("since last frame: {}", sw.Elapsed);
sw.Restart();
2024-04-07 20:16:22 +02:00
foreach (var step in _steps)
await step.TickAsync();
2024-04-07 20:29:09 +02:00
await Task.Delay(TimeSpan.FromMilliseconds(1000 / 25) - sw.Elapsed);
2024-04-07 20:16:22 +02:00
}
}
catch (Exception ex)
{
logger.LogError(ex, "game tick service crashed");
lifetime.StopApplication();
2024-04-06 21:15:26 +02:00
}
}
public async Task StopAsync(CancellationToken cancellationToken)
{
await _cancellation.CancelAsync();
if (_run != null) await _run;
}
2024-04-07 13:02:49 +02:00
public void Dispose()
{
_cancellation.Dispose();
_run?.Dispose();
}
2024-04-06 21:15:26 +02:00
}