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.
c # sleep timer
Delashmate
source share