繁体   English   中英

C#计时器-终止

[英]C# Timer - Termination

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

问题是计时器在程序退出使用块时就被破坏了。 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()并不是处理此类情况的最佳方法 ,因为它阻塞了程序的主线程。

暂无
暂无

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

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