开发者

C# Timer - Termination

开发者 https://www.devze.com 2022-12-12 17:24 出处:网络
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.

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.Chan开发者_StackOverflowge(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.

0

精彩评论

暂无评论...
验证码 换一张
取 消