What should I use Sleep or Timer

前端 未结 3 1699
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-18 11:51

I have two alternative using timer or using sleep, I need to call a method every 3 seconds after this method is finished, I wrote basic example to demonstrate what I mean:

相关标签:
3条回答
  • 2021-01-18 12:06

    Sleep will do the trick, Timer on the other hand has been designed for that exact purpose, conventions are better and they will usually make your code more understandable.

    0 讨论(0)
  • 2021-01-18 12:15

    The real context of your program matters too.

    The sleep option 'wastes' a Thread, not a problem in a small console app but in general not a good idea.

    You don't need to restart the timer, the following will keep ticking:

        static void Main(string[] args)
        {
            var t = new System.Timers.Timer(1000);
            t.Elapsed += (s, e) => CallMeBack();
            t.Start();
    
            Console.ReadLine();
        }
    
    0 讨论(0)
  • 2021-01-18 12:19

    Do you realize that fooUsingSleep is calling itself over and over? It will eventually generate a stack overflow.

    If you are using timer, it can be as simple as this:

        System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
        t.Interval = 3000;
        t.Tick += new EventHandler((o,ea) => Console.WriteLine("foo"));
    
    0 讨论(0)
提交回复
热议问题