TimestampSet.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace SKMC.Api.Common.Types
  7. {
  8. /// <summary>
  9. /// 包含时间戳的数据集
  10. /// </summary>
  11. public class TimestampSet
  12. {
  13. private readonly int capacity;
  14. private readonly (long Ticks, int Value)[] buffer;
  15. private int currentIndex;
  16. private long oldestTicks;
  17. private readonly object _lock = new object();
  18. public TimestampSet(int capacity)
  19. {
  20. this.capacity = capacity;
  21. buffer = new (long, int)[capacity];
  22. currentIndex = 0;
  23. oldestTicks = long.MaxValue;
  24. }
  25. /// <summary>
  26. /// 添加与时间戳相关的数据
  27. /// </summary>
  28. /// <param name="ticks"></param>
  29. /// <param name="value"></param>
  30. public void Add(long ticks, int value)
  31. {
  32. lock (_lock)
  33. {
  34. buffer[currentIndex] = (ticks, value);
  35. currentIndex = (currentIndex + 1) % capacity;
  36. if (currentIndex == 0)
  37. {
  38. oldestTicks = buffer[currentIndex].Ticks;
  39. }
  40. }
  41. }
  42. /// <summary>
  43. /// 添加当前"时间戳"的数据, 该"时间戳"为简化版: ticks/10000
  44. /// </summary>
  45. /// <param name="value"></param>
  46. public void Add(int value)
  47. {
  48. Add(DateTime.Now.Ticks / 10000, value);
  49. }
  50. /// <summary>
  51. /// 获取最新的一个数值
  52. /// </summary>
  53. /// <returns></returns>
  54. public int Take() => (currentIndex > 0) ? buffer[currentIndex - 1].Value : buffer[capacity - 1].Value;
  55. /// <summary>
  56. /// 获取某个时间戳之后的所有数据
  57. /// </summary>
  58. /// <param name="ticks">该"时间戳"为简化版: ticks/10000</param>
  59. /// <returns></returns>
  60. public List<int> GetDataAfter(long ticks)
  61. {
  62. List<int> result = new List<int>();
  63. lock (_lock)
  64. {
  65. for (int i = 0; i < capacity; i++)
  66. {
  67. var entry = buffer[i];
  68. if (entry.Ticks > ticks)
  69. {
  70. result.Add(entry.Value);
  71. }
  72. }
  73. }
  74. return result;
  75. }
  76. }
  77. }