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