简体   繁体   中英

C# Timer - Termination

How long the following timer will run ?.I thought it will run until i close the program.But after having 10 rounds of ticks the timer get closed.

 static void Main()
        {
            Console.WriteLine("Started at {0:HH:mm:ss:fff}", DateTime.Now);
            using (System.Threading.Timer timer = 
           new System.Threading.Timer(new TimerCallback(Tick), null, 3000, 1000))
            {

                // Wait for 10 seconds
                Thread.Sleep(10000);

                // Then go slow for another 10 seconds
                timer.Change(0, 2000);
                Thread.Sleep(10000);
            }


            Console.ReadKey(true);
        }
        static void Tick(object state)
        {
            Console.WriteLine("Ticked at {0:HH:mm:ss.fff}", DateTime.Now);
        }

The problem is that the timer gets destroyed the moment the program exits the Using-Block. Push the Console.ReadKey(True) upwards into the Using-Statement and it will work.

    static void Main()
    {
        Console.WriteLine("Started at {0:HH:mm:ss:fff}", DateTime.Now);
        using (System.Threading.Timer timer = 
       new System.Threading.Timer(new TimerCallback(Tick), null, 3000, 1000))
        {

            // Wait for 10 seconds
            Thread.Sleep(10000);

            // Then go slow for another 10 seconds
            timer.Change(0, 2000);
            // unnecessary: Thread.Sleep(10000);

            Console.ReadKey(true);
        }
    }
    static void Tick(object state)
    {
        Console.WriteLine("Ticked at {0:HH:mm:ss.fff}", DateTime.Now);
    }

Also, Threading.Sleep() is not the best way of handling such situations, since it's blocking the main thread of the program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM