C#定时器 - 终止

时间:2009-11-30 14:05:37

标签: c#

以下计时器将运行多长时间?。我认为它会一直运行直到我关闭程序。但是在经过10轮滴答后,计时器将关闭。

 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);
        }

1 个答案:

答案 0 :(得分:3)

问题是程序在程序退出使用块时被破坏。将Console.ReadKey(True)向上推入Using-Statement,它将起作用。

    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);
    }

另外,Threading.Sleep()不是处理这种情况的best way,因为它阻塞了程序的主线程。