EventQueue.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace UniversalNetFrame451;
  8. public class EventQueue<T>
  9. {
  10. public EventQueue(Action<T> queueHandler)
  11. {
  12. this._queueHandler = queueHandler;
  13. this._cancellation = new CancellationToken(false);
  14. this._queueEvent = new(false);
  15. this._pauseController = new(true);
  16. this._queue = new();
  17. Task.Factory.StartNew(WorkingTask, TaskCreationOptions.LongRunning);
  18. }
  19. private readonly Queue<T> _queue;
  20. private readonly Action<T> _queueHandler;
  21. private readonly AutoResetEvent _queueEvent;
  22. private readonly ManualResetEvent _pauseController;
  23. private CancellationToken _cancellation;
  24. public int Count
  25. {
  26. get
  27. {
  28. lock (this._queue)
  29. return this._queue.Count;
  30. }
  31. }
  32. public void Pause() => this._pauseController.Reset();
  33. public void Resume() => this._pauseController.Set();
  34. public void Cancel() => this._cancellation = new(true);
  35. public bool Enqueue(T input)
  36. {
  37. if (this._cancellation.IsCancellationRequested)
  38. return false;
  39. lock (_queue)
  40. this._queue.Enqueue(input);
  41. this._queueEvent.Set();
  42. return true;
  43. }
  44. private void WorkingTask()
  45. {
  46. for (T content; !this._cancellation.IsCancellationRequested; this._pauseController.WaitOne(-1))
  47. {
  48. if (this.Count == 0)
  49. {
  50. this._queueEvent.Reset();
  51. this._queueEvent.WaitOne(-1);
  52. }
  53. lock (_queue)
  54. content = this._queue.Dequeue();
  55. this._queueHandler?.Invoke(content);
  56. }
  57. lock (this._queue)
  58. this._queue.Clear();
  59. }
  60. }