TickService.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System.Collections.Generic;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using BubbleSocketCore.Websocket;
  5. using Microsoft.Extensions.Hosting;
  6. namespace BubbleSocketCore.Simulation
  7. {
  8. class TickService : IHostedService
  9. {
  10. private Timer simulationTimer;
  11. public static int simulationTickRateInMs { get; private set; } = 333;
  12. private Timer broadcastTimer;
  13. private int broadcastTickRateInMs = 333;
  14. public Task StartAsync(CancellationToken cancellationToken)
  15. {
  16. simulationTimer = new Timer(o => SimulationUpdate(), null, System.TimeSpan.Zero, System.TimeSpan.FromMilliseconds(simulationTickRateInMs));
  17. broadcastTimer = new Timer(o => BroadcastUpdate(), null, System.TimeSpan.Zero, System.TimeSpan.FromMilliseconds(broadcastTickRateInMs));
  18. return Task.CompletedTask;
  19. }
  20. public Task StopAsync(CancellationToken cancellationToken)
  21. {
  22. simulationTimer.Change(Timeout.Infinite, 0);
  23. broadcastTimer.Change(Timeout.Infinite, 0);
  24. return Task.CompletedTask;
  25. }
  26. public async void SimulationUpdate()
  27. {
  28. // Simulation.GetInstance().AdvanceSimulation();
  29. await Task.CompletedTask;
  30. }
  31. public async void BroadcastUpdate()
  32. {
  33. var payload = new List<object>();
  34. payload.Add("tick");
  35. ConnectionManager.GetInstance().GetActive().ForEach(connection =>
  36. {
  37. connection.SendAsync(SimulationActionType.Resync, payload, CancellationToken.None);
  38. });
  39. await Task.CompletedTask;
  40. }
  41. }
  42. }