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

56 lines
1.8 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
) : IHostedLifecycleService, IDisposable
2024-04-06 21:15:26 +02:00
{
private readonly CancellationTokenSource _cancellation = new();
private readonly TaskCompletionSource _shutdownCompletion = new();
2024-04-06 21:15:26 +02:00
private readonly List<ITickStep> _steps = steps.ToList();
public async Task StartedAsync(CancellationToken cancellationToken)
2024-04-13 14:08:51 +02:00
{
await Task.Yield();
2024-04-06 21:15:26 +02:00
2024-04-30 11:16:26 +02:00
// the first tick is really short (< 0.01ms) if this line is directly above the while
var sw = Stopwatch.StartNew();
await Task.Delay(1, CancellationToken.None).ConfigureAwait(false);
2024-04-30 10:38:09 +02:00
2024-04-07 20:16:22 +02:00
try
2024-04-06 21:15:26 +02:00
{
2024-04-07 20:16:22 +02:00
while (!_cancellation.IsCancellationRequested)
{
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-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
}
_shutdownCompletion.SetResult();
2024-04-06 21:15:26 +02:00
}
public Task StoppingAsync(CancellationToken cancellationToken) => _cancellation.CancelAsync();
public Task StopAsync(CancellationToken cancellationToken) => _shutdownCompletion.Task;
public void Dispose() => _cancellation.Dispose();
public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StartingAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StoppedAsync(CancellationToken cancellationToken) => Task.CompletedTask;
2024-04-13 14:08:51 +02:00
}