From c85e26b1b27e49ab489421a30ed5bfdf6d943f12 Mon Sep 17 00:00:00 2001 From: Johan Lindvall Date: Mon, 15 Feb 2016 17:19:46 +0100 Subject: [PATCH] Fixed Environment.TickCount overflow bug --- Source/MySql.Data/common/LowResolutionStopwatch.cs | 27 ++++++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/Source/MySql.Data/common/LowResolutionStopwatch.cs b/Source/MySql.Data/common/LowResolutionStopwatch.cs index a1f7b24..b3720aa 100644 --- a/Source/MySql.Data/common/LowResolutionStopwatch.cs +++ b/Source/MySql.Data/common/LowResolutionStopwatch.cs @@ -34,7 +34,7 @@ namespace MySql.Data.Common class LowResolutionStopwatch { long millis; - long startTime; + int startTime; public static readonly long Frequency = 1000; // measure in milliseconds public static readonly bool isHighResolution = false; @@ -53,9 +53,26 @@ public void Start() public void Stop() { - long now = Environment.TickCount; - // Calculate time different, handle possible overflow - long elapsed = (now < startTime) ? Int32.MaxValue - startTime + now : now - startTime; + // https://msdn.microsoft.com/en-us/library/system.environment.tickcount(v=vs.80).aspx - Environment.TickCount overflows from int.MaxValue to int.MinValue from .NET 2.0 and onwards. + int now = Environment.TickCount; + long elapsed; + + if (now < startTime) + { + if (now < 0) + { + elapsed = 1 + ((long)int.MaxValue - startTime) + (now - (long)int.MinValue); + } + else + { + elapsed = int.MaxValue - startTime + now; + } + } + else + { + elapsed = now - startTime; + } + millis += elapsed; } @@ -69,7 +86,7 @@ public TimeSpan Elapsed { get { - return new TimeSpan(0, 0, 0, 0, (int)millis); + return TimeSpan.FromMilliseconds(millis); } }