QueueStream.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Model.Logging;
  10. namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts
  11. {
  12. public class QueueStream
  13. {
  14. private readonly Stream _outputStream;
  15. private readonly ConcurrentQueue<byte[]> _queue = new ConcurrentQueue<byte[]>();
  16. private CancellationToken _cancellationToken;
  17. public TaskCompletionSource<bool> TaskCompletion { get; private set; }
  18. public Action<QueueStream> OnFinished { get; set; }
  19. private readonly ILogger _logger;
  20. public QueueStream(Stream outputStream, ILogger logger)
  21. {
  22. _outputStream = outputStream;
  23. _logger = logger;
  24. TaskCompletion = new TaskCompletionSource<bool>();
  25. }
  26. public void Queue(byte[] bytes)
  27. {
  28. _queue.Enqueue(bytes);
  29. }
  30. public void Start(CancellationToken cancellationToken)
  31. {
  32. _cancellationToken = cancellationToken;
  33. Task.Run(() => StartInternal());
  34. }
  35. private byte[] Dequeue()
  36. {
  37. byte[] bytes;
  38. if (_queue.TryDequeue(out bytes))
  39. {
  40. return bytes;
  41. }
  42. return null;
  43. }
  44. private async Task StartInternal()
  45. {
  46. var cancellationToken = _cancellationToken;
  47. try
  48. {
  49. while (!cancellationToken.IsCancellationRequested)
  50. {
  51. var bytes = Dequeue();
  52. if (bytes != null)
  53. {
  54. await _outputStream.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false);
  55. }
  56. else
  57. {
  58. await Task.Delay(50, cancellationToken).ConfigureAwait(false);
  59. }
  60. }
  61. TaskCompletion.TrySetResult(true);
  62. _logger.Debug("QueueStream complete");
  63. }
  64. catch (OperationCanceledException)
  65. {
  66. _logger.Debug("QueueStream cancelled");
  67. TaskCompletion.TrySetCanceled();
  68. }
  69. catch (Exception ex)
  70. {
  71. _logger.ErrorException("Error in QueueStream", ex);
  72. TaskCompletion.TrySetException(ex);
  73. }
  74. finally
  75. {
  76. if (OnFinished != null)
  77. {
  78. OnFinished(this);
  79. }
  80. }
  81. }
  82. }
  83. }