servicepoint-tanks/TanksServer/Services/GameTickService.cs

40 lines
996 B
C#
Raw Normal View History

2024-04-06 21:15:26 +02:00
using Microsoft.Extensions.Hosting;
2024-04-07 19:52:16 +02:00
using TanksServer.TickSteps;
2024-04-06 21:15:26 +02:00
2024-04-07 11:19:14 +02:00
namespace TanksServer.Services;
2024-04-06 21:15:26 +02:00
2024-04-07 13:02:49 +02:00
internal sealed class GameTickService(IEnumerable<ITickStep> steps) : 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()
{
while (!_cancellation.IsCancellationRequested)
{
foreach (var step in _steps)
await step.TickAsync();
2024-04-07 17:17:11 +02:00
await Task.Delay(1000/25);
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
}