game tick service
This commit is contained in:
parent
154539488a
commit
1a20fa1fb6
1 changed files with 119 additions and 34 deletions
38
TanksServer/GameTickService.cs
Normal file
38
TanksServer/GameTickService.cs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
using System.Threading;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace TanksServer;
|
||||
|
||||
public class GameTickService(IEnumerable<ITickStep> steps) : IHostedService
|
||||
{
|
||||
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();
|
||||
await Task.Delay(1000 / 250);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await _cancellation.CancelAsync();
|
||||
if (_run != null) await _run;
|
||||
}
|
||||
}
|
||||
|
||||
public interface ITickStep
|
||||
{
|
||||
Task TickAsync();
|
||||
}
|
||||
Reference in a new issue