What should I use a dream or timer

I have two alternatives using a timer or using sleep, I need to call the method every 3 seconds after the completion of this method, I wrote a basic example to demonstrate what I mean:

public static void Main() { new Thread(new ThreadStart(fooUsingSleep)).Start(); callToMethodAfterInterval(new Action<object, ElapsedEventArgs>(fooUsingTimer), 3000); } public static void fooUsingSleep() { Console.WriteLine("Doing some consuming time work using sleep"); Thread.Sleep(3000); fooUsingSleep(); } public static void fooUsingTimer(object dummy, ElapsedEventArgs dummyElapsed) { Console.WriteLine("Doing some consuming time work usning timer"); callToMethodAfterInterval(new Action<object, ElapsedEventArgs>(fooUsingTimer), 3000); } public static void callToMethodAfterInterval(Action<object,ElapsedEventArgs> inMethod, int inInterval) { System.Timers.Timer myTimer = new System.Timers.Timer(); myTimer.Elapsed += new ElapsedEventHandler(inMethod); myTimer.Interval = inInterval; myTimer.AutoReset = false; myTimer.Start(); } 

So my questions

1) Can I write code with a timer more elegant? Allows you to remove the callToMethodAfterInterval method call from fooUsingTimer, make the timer one or two lines, and remove dummy variables from the fooUsingTimer declaration?

2) I understand that sleep is not busy waiting (http://www.codeproject.com/KB/threads/ThreadingDotNet.aspx) Therefore, I did not find excuses to use the timer parameter here, because sleep is simpler, which is better to use. timer or sleep version?

3) I know that Timers.timer is thread safe, can it help me in the behavior that I want to implement?

Thanks.

+6
c # sleep timer
source share
3 answers

The real context of your program also matters.

The sleep parameter disables Thread, not a problem in a small console application, but overall this is not a good idea.

You do not need to restart the timer, the following will tick:

  static void Main(string[] args) { var t = new System.Timers.Timer(1000); t.Elapsed += (s, e) => CallMeBack(); t.Start(); Console.ReadLine(); } 
+2
source share

Do you realize that fooUsingSleep calls itself again and again? This will eventually lead to a stack overflow.

If you use a timer, it could be that simple:

  System.Windows.Forms.Timer t = new System.Windows.Forms.Timer(); t.Interval = 3000; t.Tick += new EventHandler((o,ea) => Console.WriteLine("foo")); 
+3
source share

Sleep will do the trick, on the other hand, the timer was designed for this purpose, the conventions are better, and they usually make your code more understandable.

0
source share

All Articles