TimeoutInterval.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. namespace Wayne.Lib
  3. {
  4. /// <summary>
  5. /// TimeoutInterval to keep track of internal timeouts. This is to be used in-memory, and the internal value could not be
  6. /// saved external to the process as the implementation uses Environment.TickCount that is not exportable..
  7. /// It measures the time from the object is created until the supplied interval is elapsed. Then IsTimeout property
  8. /// will change from false to true.
  9. /// </summary>
  10. public class TimeoutInterval
  11. {
  12. private readonly int startTime;
  13. private readonly int endTime;
  14. /// <summary>
  15. /// Used to enable mocking Environment tickcount in unit tests.
  16. /// </summary>
  17. public static Func<int> TickProvider = () => Environment.TickCount;
  18. /// <summary>
  19. /// Constructor taking
  20. /// </summary>
  21. /// <param name="interval"></param>
  22. public TimeoutInterval(TimeSpan interval)
  23. {
  24. startTime = TickProvider();
  25. unchecked
  26. {
  27. endTime = startTime + (int)interval.TotalMilliseconds; //Let it wrap around.
  28. }
  29. }
  30. /// <summary>
  31. /// Returns a value that tells if the timeout interval has been passed.
  32. /// </summary>
  33. public bool IsTimedOut
  34. {
  35. get
  36. {
  37. var now = TickProvider();
  38. //Normal case - end time is after start time.
  39. if (endTime > startTime)
  40. {
  41. return now > endTime;
  42. }
  43. else //Other case - we have hit the flip point, so start time is end of the first and start beginning of next.
  44. {
  45. return (now < startTime) && (now > endTime);
  46. }
  47. }
  48. }
  49. }
  50. }