简体   繁体   English

C#计时器-终止

[英]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. 以下计时器将运行多长时间?我以为它将一直运行到我关闭程序为止。但是经过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);
        }

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

Also, Threading.Sleep() is not the best way of handling such situations, since it's blocking the main thread of the program. 另外,Threading.Sleep()并不是处理此类情况的最佳方法 ,因为它阻塞了程序的主线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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