servicepoint-tanks/tanks-backend/TanksServer/GameLogic/GameTickWorker.cs

59 lines
1.4 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-10 19:25:45 +02:00
namespace TanksServer.GameLogic;
2024-04-06 21:15:26 +02:00
2024-04-07 20:29:09 +02:00
internal sealed class GameTickWorker(
2024-04-09 22:38:56 +02:00
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;
2024-04-13 14:08:51 +02:00
public void Dispose()
{
_cancellation.Dispose();
_run?.Dispose();
}
2024-04-06 21:15:26 +02:00
public Task StartAsync(CancellationToken cancellationToken)
{
_run = RunAsync();
return Task.CompletedTask;
}
2024-04-13 14:08:51 +02:00
public async Task StopAsync(CancellationToken cancellationToken)
{
await _cancellation.CancelAsync();
if (_run != null) await _run;
}
2024-04-06 21:15:26 +02:00
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);
2024-04-16 19:40:08 +02:00
var delta = sw.Elapsed;
2024-04-07 20:29:09 +02:00
sw.Restart();
2024-04-07 20:16:22 +02:00
foreach (var step in _steps)
2024-04-16 19:40:08 +02:00
await step.TickAsync(delta);
2024-04-09 22:38:56 +02:00
2024-04-16 19:40:08 +02:00
await Task.Delay(1);
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
}
}
2024-04-13 14:08:51 +02:00
}