HeartbeatManager.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace BestHTTP.Extensions
  6. {
  7. public interface IHeartbeat
  8. {
  9. void OnHeartbeatUpdate(TimeSpan dif);
  10. }
  11. /// <summary>
  12. /// A manager class that can handle subscribing and unsubscribeing in the same update.
  13. /// </summary>
  14. public sealed class HeartbeatManager
  15. {
  16. private List<IHeartbeat> Heartbeats = new List<IHeartbeat>();
  17. private IHeartbeat[] UpdateArray;
  18. private DateTime LastUpdate = DateTime.MinValue;
  19. public void Subscribe(IHeartbeat heartbeat)
  20. {
  21. lock (Heartbeats)
  22. {
  23. if (!Heartbeats.Contains(heartbeat))
  24. Heartbeats.Add(heartbeat);
  25. }
  26. }
  27. public void Unsubscribe(IHeartbeat heartbeat)
  28. {
  29. lock (Heartbeats)
  30. Heartbeats.Remove(heartbeat);
  31. }
  32. public void Update()
  33. {
  34. if (LastUpdate == DateTime.MinValue)
  35. LastUpdate = DateTime.UtcNow;
  36. else
  37. {
  38. TimeSpan dif = DateTime.UtcNow - LastUpdate;
  39. LastUpdate = DateTime.UtcNow;
  40. int count = 0;
  41. lock (Heartbeats)
  42. {
  43. if (UpdateArray == null || UpdateArray.Length < Heartbeats.Count)
  44. Array.Resize(ref UpdateArray, Heartbeats.Count);
  45. Heartbeats.CopyTo(0, UpdateArray, 0, Heartbeats.Count);
  46. count = Heartbeats.Count;
  47. }
  48. for (int i = 0; i < count; ++i)
  49. {
  50. try
  51. {
  52. UpdateArray[i].OnHeartbeatUpdate(dif);
  53. }
  54. catch
  55. { }
  56. }
  57. }
  58. }
  59. }
  60. }