我有两种选择,使用计时器或者使用休眠,我需要在方法完成后每3秒调用一次该方法。以下是一个基本示例来演示我的意思:
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();
}
我的问题是:
1)我能否更优雅地编写带有定时器的代码?这意味着从fooUsingTimer方法中删除对callToMethodAfterInterval方法的调用,将定时器缩短为一两行,并从fooUsingTimer的声明中删除虚拟变量?
2)我知道sleep不是忙等待(http://www.codeproject.com/KB/threads/ThreadingDotNet.aspx),所以我找不到在此处使用定时器选项的理由,因为sleep更简单。哪个更好,定时器版本还是sleep版本?
3)我知道Timers.timer是线程安全的,它能帮助我实现想要的行为吗?
谢谢。