TimeoutHelper.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. namespace System.Threading
  6. {
  7. /// <summary>
  8. /// A helper class to capture a start time using <see cref="Environment.TickCount"/> as a time in milliseconds.
  9. /// Also updates a given timeout by subtracting the current time from the start time.
  10. /// </summary>
  11. internal static class TimeoutHelper
  12. {
  13. /// <summary>
  14. /// Returns <see cref="Environment.TickCount"/> as a start time in milliseconds as a <see cref="UInt32"/>.
  15. /// <see cref="Environment.TickCount"/> rolls over from positive to negative every ~25 days, then ~25 days to back to positive again.
  16. /// <see cref="UInt32"/> is used to ignore the sign and double the range to 50 days.
  17. /// </summary>
  18. public static uint GetTime()
  19. {
  20. return (uint)Environment.TickCount;
  21. }
  22. /// <summary>
  23. /// Helper function to measure and update the elapsed time
  24. /// </summary>
  25. /// <param name="startTime"> The first time (in milliseconds) observed when the wait started</param>
  26. /// <param name="originalWaitMillisecondsTimeout">The original wait timeout in milliseconds</param>
  27. /// <returns>The new wait time in milliseconds, or -1 if the time expired</returns>
  28. public static int UpdateTimeOut(uint startTime, int originalWaitMillisecondsTimeout)
  29. {
  30. // The function must be called in case the time out is not infinite
  31. Debug.Assert(originalWaitMillisecondsTimeout != Timeout.Infinite);
  32. uint elapsedMilliseconds = (GetTime() - startTime);
  33. // Check the elapsed milliseconds is greater than max int because this property is uint
  34. if (elapsedMilliseconds > int.MaxValue)
  35. {
  36. return 0;
  37. }
  38. // Subtract the elapsed time from the current wait time
  39. int currentWaitTimeout = originalWaitMillisecondsTimeout - (int)elapsedMilliseconds;
  40. if (currentWaitTimeout <= 0)
  41. {
  42. return 0;
  43. }
  44. return currentWaitTimeout;
  45. }
  46. }
  47. }