ProtocolEvents.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using BestHTTP.Logger;
  5. // Required for ConcurrentQueue.Clear extension.
  6. using BestHTTP.Extensions;
  7. namespace BestHTTP.Core
  8. {
  9. public
  10. #if CSHARP_7_OR_LATER
  11. readonly
  12. #endif
  13. struct ProtocolEventInfo
  14. {
  15. public readonly IProtocol Source;
  16. public ProtocolEventInfo(IProtocol source)
  17. {
  18. this.Source = source;
  19. }
  20. public override string ToString()
  21. {
  22. return string.Format("[ProtocolEventInfo Source: {0}]", Source);
  23. }
  24. }
  25. public static class ProtocolEventHelper
  26. {
  27. private static ConcurrentQueue<ProtocolEventInfo> protocolEvents = new ConcurrentQueue<ProtocolEventInfo>();
  28. private static List<IProtocol> ActiveProtocols = new List<IProtocol>(2);
  29. #pragma warning disable 0649
  30. public static Action<ProtocolEventInfo> OnEvent;
  31. #pragma warning restore
  32. public static void EnqueueProtocolEvent(ProtocolEventInfo @event)
  33. {
  34. if (HTTPManager.Logger.Level == Loglevels.All)
  35. HTTPManager.Logger.Information("ProtocolEventHelper", "Enqueue protocol event: " + @event.ToString(), @event.Source.LoggingContext);
  36. protocolEvents.Enqueue(@event);
  37. }
  38. internal static void Clear()
  39. {
  40. protocolEvents.Clear();
  41. }
  42. internal static void ProcessQueue()
  43. {
  44. ProtocolEventInfo protocolEvent;
  45. while (protocolEvents.TryDequeue(out protocolEvent))
  46. {
  47. if (HTTPManager.Logger.Level == Loglevels.All)
  48. HTTPManager.Logger.Information("ProtocolEventHelper", "Processing protocol event: " + protocolEvent.ToString(), protocolEvent.Source.LoggingContext);
  49. if (OnEvent != null)
  50. {
  51. try
  52. {
  53. OnEvent(protocolEvent);
  54. }
  55. catch (Exception ex)
  56. {
  57. HTTPManager.Logger.Exception("ProtocolEventHelper", "ProcessQueue", ex, protocolEvent.Source.LoggingContext);
  58. }
  59. }
  60. IProtocol protocol = protocolEvent.Source;
  61. protocol.HandleEvents();
  62. if (protocol.IsClosed)
  63. {
  64. ActiveProtocols.Remove(protocol);
  65. HostManager.GetHost(protocol.ConnectionKey.Host)
  66. .GetHostDefinition(protocol.ConnectionKey.Connection)
  67. .TryToSendQueuedRequests();
  68. protocol.Dispose();
  69. }
  70. }
  71. }
  72. internal static void AddProtocol(IProtocol protocol)
  73. {
  74. ActiveProtocols.Add(protocol);
  75. }
  76. internal static void CancelActiveProtocols()
  77. {
  78. for (int i = 0; i < ActiveProtocols.Count; ++i)
  79. {
  80. var protocol = ActiveProtocols[i];
  81. protocol.CancellationRequested();
  82. }
  83. }
  84. }
  85. }