Microsoft Knowledge Base Email Alertz

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

Search KbAlertz

Advanced Search

Receive Microsoft Knowledge Base articles by E-Mail?

Every night we scan the Microsoft Knowledge Base. If technologies you're interested in are updated, we'll send you an e-mail. You only get one e-mail a day, and only when new articles are added.

Click here to create a
FREE account
Already have an account?
[Click here to Login]











Microsoft Knowledge Base Article

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

Article ID: 950807 - Last Review: March 24, 2008 - Revision: 1.1

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

Source: Microsoft Support

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.

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.

Result

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

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.

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.

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.

APPLIES TO
  • Microsoft .NET Framework 2.0
  • Microsoft .NET Framework 3.0
  • Microsoft .NET Framework 3.5
Keywords: 
kbnomt kbrapidpub KB950807
       

Community Feedback System

Very often, it takes hours to solve a problem. Very often, you've looked high and low, and have tried a lot of solutions. When you finally found it, chances are, it was because someone else helped you. Here's your chance to give back. Use our community feedback tool to let others know what worked for you and what didn't.

Please also understand that the community feedback system is not warranted to be correct, it's simply a system that we've built to let people try and help each other. If something in a feedback response doesn't make sense to you, or you're not comfortable making changes that the feedback talks about (like registry edits), please consult a professional.

Thank you for using kbAlertz.com Feedback System.

-- Scott Cate