System.Threading.Timer fires immediately when specifying a large value for due time

System.Threading.Timer fires immediately when specifying a large value for due time

Article ID : 950807
Last Review : March 24, 2008
Revision : 1.0
Source: Microsoft Support

Back to the top

RAPID PUBLISHING

RAPID PUBLISHING ARTICLES PROVIDE INFORMATION DIRECTLY FROM WITHIN THE MICROSOFT SUPPORT ORGANIZATION. THE INFORMATION CONTAINED HEREIN IS CREATED IN RESPONSE TO EMERGING OR UNIQUE TOPICS, OR IS INTENDED SUPPLEMENT OTHER KNOWLEDGE BASE INFORMATION.

Back to the top

Action

Write a .Net application and use the System.Threading.Timer object, specifying a large value for due time in either the Change() or one of the constructor methods.

Back to the top

Result

Instead of the Timer being fired at the time specified, the Timer fires immediately.

Back to the top

Cause

This is a known bug in the products listed below.

The problem is caused by the way the .Net Framework schedules timers to be fired.  Internally, timers use a 32-bit integer to determine fire time – which is based upon the system’s tick count. It has an internal thread that fires the timers, and tracks the last time the timers were checked (previous tick count). When it sweeps the timers to determine which ones should fire, it looks at their fire time tick count, and sees which ones fall between the previous tick count and the current tick count, and fires those timers.

A timer’s fire time is equal to the current tick count plus the due time specified.  If that addition would cause an integer overflow, the resulting fire time wraps around from zero.  The problem is that if a timer is scheduled with a target tick count that wraps around far enough to fall between the previous tick count and the current tick count, then it will be fired immediately.

Back to the top

Resolution

This problem can be avoided by using a timer that will fire at an interval equivalent to the maximum time a timer can be scheduled (which is UInt32.MaxValue – 1, or roughly 49.7 days) minus the maximum time that you wish to schedule timers for.  This solution works by making sure the previous tick count is sufficiently close enough to the current tick count so fire times that roll over won’t fall between those two values. 

For example, if you want to use timers in your application that would fire every 48 days, then schedule a repeating timer (that does nothing) to fire at an interval of max timer time minus 48 days minus a few milliseconds (to be safe).  Here is code that demonstrates this example:

    class MyClass
    {
        System.Threading.Timer _timer;

        uint DueTime = 4147200000; // 48 days in milliseconds

        void MyFunction()
        {
            _timer = new System.Threading.Timer(CallbackMethod, null, DueTime, System.Threading.Timeout.Infinite);
        }

        void CallbackMethod(object state)
        {
            Console.WriteLine(CallbackMethod fired);
        }
    }

In the above code, MyClass.MyFunction() creates a new timer that will be fired once in 48 days.  If the application has been running for two days or more, invoking the MyFunction() method could cause the timer it creates to be fired immediately instead of in 48 days.  This is one way to solve that problem:

    class MyClass
    {
        System.Threading.Timer _timer;
        System.Threading.Timer _repeatingTimer;

        uint DueTime = 4147200000; // 48 days in milliseconds

        void MyFunction()
        {
            if (_repeatingTimer == null)
                InitMaximumTime(DueTime);

            _timer = new System.Threading.Timer(CallbackMethod, null, DueTime, System.Threading.Timeout.Infinite);
        }

        void InitMaximumTime(uint time)
        {
            //             max timer time                1 sec safety buffer
            uint period = (UInt32.MaxValue – 1) – time – 1000;
            _repeatingTimer = new System.Threading.Timer(RepeatingTimerCallback, null, period, period);
        }

        // Callback method that does nothing 
        void RepeatingTimerCallback(object state) { }

        void CallbackMethod(object state)
        {
            Console.WriteLine(CallbackMethod fired);
        }
    }

Now MyFunction() will call InitMaximumTime() which sets up a repeating timer that fires often enough to keep the fire time of the timer MyFunction() creates from rolling over and being fired immediately instead of in 48 days. 

The maximum time a timer should ever be scheduled for is UInt32.MaxValue – 1000 milliseconds.  To ensure that timer will fire properly, a repeating timer should be on a 900 millisecond interval.

Back to the top

DISCLAIMER

MICROSOFT AND/OR ITS SUPPLIERS MAKE NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY, RELIABILITY OR ACCURACY OF THE INFORMATION CONTAINED IN THE DOCUMENTS AND RELATED GRAPHICS PUBLISHED ON THIS WEBSITE (THE “MATERIALS”) FOR ANY PURPOSE. THE MATERIALS MAY INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS AND MAY BE REVISED AT ANY TIME WITHOUT NOTICE.

TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, MICROSOFT AND/OR ITS SUPPLIERS DISCLAIM AND EXCLUDE ALL REPRESENTATIONS, WARRANTIES, AND CONDITIONS WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO REPRESENTATIONS, WARRANTIES, OR CONDITIONS OF TITLE, NON INFRINGEMENT, SATISFACTORY CONDITION OR QUALITY, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, WITH RESPECT TO THE MATERIALS.

Back to the top


APPLIES TO
• Microsoft .NET Framework 2.0
• Microsoft .NET Framework 3.0
• Microsoft .NET Framework 3.5

Back to the top

Keywords: 
kbnomt kbrapidpub KB950807

Back to the top

 

Microsoft Knowledge Base Article

This article contents is Microsoft Copyrighted material.
Microsoft Corporation. All rights reserved. Terms of Use | Trademarks


You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

AddThis Social Bookmark Button

Leave a Reply

*
To prove that you're not a bot, enter this code
Anti-Spam Image