AsyncStreamWriterFunc.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Threading.Tasks;
  5. using ServiceStack;
  6. using ServiceStack.Web;
  7. namespace MediaBrowser.Server.Implementations.HttpServer
  8. {
  9. public class AsyncStreamWriterFunc : IStreamWriter, IAsyncStreamWriter, IHasOptions
  10. {
  11. /// <summary>
  12. /// Gets or sets the source stream.
  13. /// </summary>
  14. /// <value>The source stream.</value>
  15. private Func<Stream, Task> Writer { get; set; }
  16. /// <summary>
  17. /// Gets the options.
  18. /// </summary>
  19. /// <value>The options.</value>
  20. public IDictionary<string, string> Options { get; private set; }
  21. public Action OnComplete { get; set; }
  22. public Action OnError { get; set; }
  23. /// <summary>
  24. /// Initializes a new instance of the <see cref="StreamWriter" /> class.
  25. /// </summary>
  26. public AsyncStreamWriterFunc(Func<Stream, Task> writer, IDictionary<string, string> headers)
  27. {
  28. Writer = writer;
  29. if (headers == null)
  30. {
  31. headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  32. }
  33. Options = headers;
  34. }
  35. /// <summary>
  36. /// Writes to.
  37. /// </summary>
  38. /// <param name="responseStream">The response stream.</param>
  39. public void WriteTo(Stream responseStream)
  40. {
  41. var task = Writer(responseStream);
  42. Task.WaitAll(task);
  43. }
  44. public async Task WriteToAsync(Stream responseStream)
  45. {
  46. await Writer(responseStream).ConfigureAwait(false);
  47. }
  48. }
  49. }