AsyncWorkQueue.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Threading;
  4. namespace Ryujinx.Common
  5. {
  6. public sealed class AsyncWorkQueue<T> : IDisposable
  7. {
  8. private readonly Thread _workerThread;
  9. private readonly CancellationTokenSource _cts;
  10. private readonly Action<T> _workerAction;
  11. private readonly BlockingCollection<T> _queue;
  12. public bool IsCancellationRequested => _cts.IsCancellationRequested;
  13. public AsyncWorkQueue(Action<T> callback, string name = null) : this(callback, name, new BlockingCollection<T>())
  14. {
  15. }
  16. public AsyncWorkQueue(Action<T> callback, string name, BlockingCollection<T> collection)
  17. {
  18. _cts = new CancellationTokenSource();
  19. _queue = collection;
  20. _workerAction = callback;
  21. _workerThread = new Thread(DoWork)
  22. {
  23. Name = name,
  24. IsBackground = true,
  25. };
  26. _workerThread.Start();
  27. }
  28. private void DoWork()
  29. {
  30. try
  31. {
  32. foreach (T item in _queue.GetConsumingEnumerable(_cts.Token))
  33. {
  34. _workerAction(item);
  35. }
  36. }
  37. catch (OperationCanceledException)
  38. {
  39. }
  40. }
  41. public void Cancel()
  42. {
  43. _cts.Cancel();
  44. }
  45. public void CancelAfter(int millisecondsDelay)
  46. {
  47. _cts.CancelAfter(millisecondsDelay);
  48. }
  49. public void CancelAfter(TimeSpan delay)
  50. {
  51. _cts.CancelAfter(delay);
  52. }
  53. public void Add(T workItem)
  54. {
  55. _queue.Add(workItem);
  56. }
  57. public void Add(T workItem, CancellationToken cancellationToken)
  58. {
  59. _queue.Add(workItem, cancellationToken);
  60. }
  61. public bool TryAdd(T workItem)
  62. {
  63. return _queue.TryAdd(workItem);
  64. }
  65. public bool TryAdd(T workItem, int millisecondsDelay)
  66. {
  67. return _queue.TryAdd(workItem, millisecondsDelay);
  68. }
  69. public bool TryAdd(T workItem, int millisecondsDelay, CancellationToken cancellationToken)
  70. {
  71. return _queue.TryAdd(workItem, millisecondsDelay, cancellationToken);
  72. }
  73. public bool TryAdd(T workItem, TimeSpan timeout)
  74. {
  75. return _queue.TryAdd(workItem, timeout);
  76. }
  77. public void Dispose()
  78. {
  79. _queue.CompleteAdding();
  80. _cts.Cancel();
  81. _workerThread.Join();
  82. _queue.Dispose();
  83. _cts.Dispose();
  84. }
  85. }
  86. }