TimerRepository.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Collections.Generic;
  3. namespace XGame.Framework.Time
  4. {
  5. /// <summary>
  6. /// 定时器仓储
  7. /// </summary>
  8. public class TimerRepository : IClockTick, IDisposable
  9. {
  10. private readonly List<Timer> _aliveTimers = new List<Timer>();
  11. internal ITimer AddDelayTimer(int delay, Action action)
  12. {
  13. var timer = new Timer(delay, delay, 1, action);
  14. _aliveTimers.Add(timer);
  15. return timer;
  16. }
  17. internal ITimer AddLooperTimer(int delay, int interval, Action<int> action, int loopTime = -1)
  18. {
  19. var timer = new Timer(delay, interval, loopTime, action);
  20. _aliveTimers.Add(timer);
  21. return timer;
  22. }
  23. public void ClockUpdate(int millisecond)
  24. {
  25. // 客户端定时器数量较少不考虑时间轮优化
  26. for (int i = _aliveTimers.Count - 1; i >= 0; --i)
  27. {
  28. if (_aliveTimers[i].Update(millisecond))
  29. {
  30. _aliveTimers.RemoveAt(i);
  31. }
  32. }
  33. }
  34. public void Dispose()
  35. {
  36. foreach (var item in _aliveTimers)
  37. {
  38. item.Dispose();
  39. }
  40. _aliveTimers.Clear();
  41. }
  42. }
  43. }