我该怎么用Sleep或Timer

我有两个使用计时器或使用睡眠的替代方案,我需要在这个方法完成后每隔3秒调用一个方法,我写了一个基本的例子来certificate我的意思:

public static void Main() { new Thread(new ThreadStart(fooUsingSleep)).Start(); callToMethodAfterInterval(new Action(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(fooUsingTimer), 3000); } public static void callToMethodAfterInterval(Action 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)我理解睡眠不忙等待(http://www.codeproject.com/KB/threads/ThreadingDotNet.aspx)所以我没有找到在这里使用计时器选项的理由,因为睡眠更简单,什么是更好的使用,计时器版本或睡眠?

3)我知道Timers.timer是线程安全的,它能帮助我实现我想要实现的行为吗?

谢谢。

您的计划的真实背景也很重要。

睡眠选项’浪费’一个线程,在小型控制台应用程序中不是问题,但通常不是一个好主意。

您不需要重新启动计时器,以下内容将继续滴答:

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

你是否意识到fooUsingSleep呼唤着自己? 它最终会产生堆栈溢出。

如果您正在使用计时器,它可以像这样简单:

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

睡眠将起到作用,另一方面,Timer是为了这个目的而设计的,约定更好,它们通常会使你的代码更容易理解。