EventConsumer.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. namespace Admin.NET.Core;
  7. /// <summary>
  8. /// Redis 消息扩展
  9. /// </summary>
  10. /// <typeparam name="T"></typeparam>
  11. public class EventConsumer<T> : IDisposable
  12. {
  13. /// <summary>
  14. ///
  15. /// </summary>
  16. private Task _consumerTask;
  17. /// <summary>
  18. ///
  19. /// </summary>
  20. private CancellationTokenSource _consumerCts;
  21. /// <summary>
  22. /// 消费者
  23. /// </summary>
  24. public IProducerConsumer<T> Consumer { get; }
  25. /// <summary>
  26. /// 消息回调
  27. /// </summary>
  28. public event EventHandler<T> Received;
  29. /// <summary>
  30. /// 构造函数
  31. /// </summary>
  32. /// <param name="consumer"></param>
  33. public EventConsumer(IProducerConsumer<T> consumer) => Consumer = consumer;
  34. /// <summary>
  35. /// 启动
  36. /// </summary>
  37. /// <exception cref="InvalidOperationException"></exception>
  38. public void Start()
  39. {
  40. if (Consumer is null)
  41. {
  42. throw new InvalidOperationException("Subscribe first using the Consumer.Subscribe() function");
  43. }
  44. if (_consumerTask != null)
  45. {
  46. return;
  47. }
  48. _consumerCts = new CancellationTokenSource();
  49. var ct = _consumerCts.Token;
  50. _consumerTask = Task.Factory.StartNew(() =>
  51. {
  52. while (!ct.IsCancellationRequested)
  53. {
  54. var cr = Consumer.TakeOne(10);
  55. if (cr == null) continue;
  56. Received?.Invoke(this, cr);
  57. }
  58. }, ct, TaskCreationOptions.LongRunning, TaskScheduler.Default);
  59. }
  60. /// <summary>
  61. /// 停止
  62. /// </summary>
  63. /// <returns></returns>
  64. public async Task Stop()
  65. {
  66. if (_consumerCts == null || _consumerTask == null) return;
  67. _consumerCts.Cancel();
  68. try
  69. {
  70. await _consumerTask;
  71. }
  72. finally
  73. {
  74. _consumerTask = null;
  75. _consumerCts = null;
  76. }
  77. }
  78. /// <summary>
  79. /// 释放
  80. /// </summary>
  81. public void Dispose()
  82. {
  83. Dispose(true);
  84. GC.SuppressFinalize(this);
  85. }
  86. /// <summary>
  87. /// 释放
  88. /// </summary>
  89. /// <param name="disposing"></param>
  90. protected virtual void Dispose(bool disposing)
  91. {
  92. if (disposing)
  93. {
  94. if (_consumerTask != null)
  95. {
  96. Stop().Wait();
  97. }
  98. }
  99. }
  100. }