TimingCollector.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.Collections.Generic;
  3. using BestHTTP.Core;
  4. namespace BestHTTP.Timings
  5. {
  6. public sealed class TimingCollector
  7. {
  8. public HTTPRequest ParentRequest { get; }
  9. /// <summary>
  10. /// When the TimingCollector instance created.
  11. /// </summary>
  12. public DateTime Start { get; private set; }
  13. /// <summary>
  14. /// List of added events.
  15. /// </summary>
  16. public List<TimingEvent> Events { get; private set; }
  17. public TimingCollector(HTTPRequest parentRequest)
  18. {
  19. this.ParentRequest = parentRequest;
  20. this.Start = DateTime.Now;
  21. }
  22. internal void AddEvent(string name, DateTime when, TimeSpan duration)
  23. {
  24. if (this.Events == null)
  25. this.Events = new List<TimingEvent>();
  26. if (duration == TimeSpan.Zero)
  27. {
  28. DateTime prevEventAt = this.Start;
  29. if (this.Events.Count > 0)
  30. prevEventAt = this.Events[this.Events.Count - 1].When;
  31. duration = when - prevEventAt;
  32. }
  33. this.Events.Add(new TimingEvent(name, when, duration));
  34. }
  35. /// <summary>
  36. /// Add an event. Duration is calculated from the previous event or start of the collector.
  37. /// </summary>
  38. public void Add(string name)
  39. {
  40. RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.ParentRequest, name, DateTime.Now));
  41. }
  42. /// <summary>
  43. /// Add an event with a known duration.
  44. /// </summary>
  45. public void Add(string name, TimeSpan duration)
  46. {
  47. RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.ParentRequest, name, duration));
  48. }
  49. public TimingEvent FindFirst(string name)
  50. {
  51. if (this.Events == null)
  52. return TimingEvent.Empty;
  53. for (int i = 0; i < this.Events.Count; ++i)
  54. {
  55. if (this.Events[i].Name == name)
  56. return this.Events[i];
  57. }
  58. return TimingEvent.Empty;
  59. }
  60. public TimingEvent FindLast(string name)
  61. {
  62. if (this.Events == null)
  63. return TimingEvent.Empty;
  64. for (int i = this.Events.Count - 1; i >= 0; --i)
  65. {
  66. if (this.Events[i].Name == name)
  67. return this.Events[i];
  68. }
  69. return TimingEvent.Empty;
  70. }
  71. public override string ToString()
  72. {
  73. string result = string.Format("[TimingCollector Start: '{0}' ", this.Start.ToLongTimeString());
  74. if (this.Events != null)
  75. foreach (var @event in this.Events)
  76. result += '\n' + @event.ToString();
  77. result += "]";
  78. return result;
  79. }
  80. }
  81. }