QueueStream.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 Emby.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 Guid Id = Guid.NewGuid();
  21. public QueueStream(Stream outputStream, ILogger logger)
  22. {
  23. _outputStream = outputStream;
  24. _logger = logger;
  25. TaskCompletion = new TaskCompletionSource<bool>();
  26. }
  27. public void Queue(byte[] bytes)
  28. {
  29. _queue.Enqueue(bytes);
  30. }
  31. public void Start(CancellationToken cancellationToken)
  32. {
  33. _cancellationToken = cancellationToken;
  34. Task.Run(() => StartInternal());
  35. }
  36. private byte[] Dequeue()
  37. {
  38. byte[] bytes;
  39. if (_queue.TryDequeue(out bytes))
  40. {
  41. return bytes;
  42. }
  43. return null;
  44. }
  45. private async Task StartInternal()
  46. {
  47. var cancellationToken = _cancellationToken;
  48. try
  49. {
  50. while (true)
  51. {
  52. var bytes = Dequeue();
  53. if (bytes != null)
  54. {
  55. await _outputStream.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false);
  56. }
  57. else
  58. {
  59. await Task.Delay(50, cancellationToken).ConfigureAwait(false);
  60. }
  61. }
  62. }
  63. catch (OperationCanceledException)
  64. {
  65. _logger.Debug("QueueStream cancelled");
  66. TaskCompletion.TrySetCanceled();
  67. }
  68. catch (Exception ex)
  69. {
  70. _logger.ErrorException("Error in QueueStream", ex);
  71. TaskCompletion.TrySetException(ex);
  72. }
  73. finally
  74. {
  75. if (OnFinished != null)
  76. {
  77. OnFinished(this);
  78. }
  79. }
  80. }
  81. }
  82. }