Change Task.Delay to use TimerQueueTimer instead of Timer
authorStephen Toub <stoub@microsoft.com>
Mon, 16 Oct 2017 19:16:31 +0000 (15:16 -0400)
committerStephen Toub <stoub@microsoft.com>
Mon, 16 Oct 2017 19:16:31 +0000 (15:16 -0400)
Timer is just a wrapper for a TimerHolder which is just a wrapper for a TimerQueueTimer.  We don't actually want the behavior provided by TimerHolder (to allow the underlying timer to be collected while it's in use) and explicitly work around that, and for that pleasure we're paying two additional allocations.  Just skip directly to the inner type.

src/mscorlib/src/System/Threading/Tasks/Task.cs
src/mscorlib/src/System/Threading/Timer.cs

index aed2c3b..219e024 100644 (file)
@@ -5444,8 +5444,7 @@ namespace System.Threading.Tasks
             // ... and create our timer and make sure that it stays rooted.
             if (millisecondsDelay != Timeout.Infinite) // no need to create the timer if it's an infinite timeout
             {
-                promise.Timer = new Timer(state => ((DelayPromise)state).Complete(), promise, millisecondsDelay, Timeout.Infinite);
-                promise.Timer.KeepRootedWhileScheduled();
+                promise.Timer = new TimerQueueTimer(state => ((DelayPromise)state).Complete(), promise, (uint)millisecondsDelay, Timeout.UnsignedInfinite);
             }
 
             // Return the timer proxy task
@@ -5470,7 +5469,7 @@ namespace System.Threading.Tasks
 
             internal readonly CancellationToken Token;
             internal CancellationTokenRegistration Registration;
-            internal Timer Timer;
+            internal TimerQueueTimer Timer;
 
             internal void Complete()
             {
@@ -5496,7 +5495,7 @@ namespace System.Threading.Tasks
                 // If we set the value, also clean up.
                 if (setSucceeded)
                 {
-                    if (Timer != null) Timer.Dispose();
+                    Timer?.Close();
                     Registration.Dispose();
                 }
             }
index 11b46ab..84839e7 100644 (file)
@@ -804,10 +804,5 @@ namespace System.Threading
         {
             m_timer.Close();
         }
-
-        internal void KeepRootedWhileScheduled()
-        {
-            GC.SuppressFinalize(m_timer);
-        }
     }
 }