c# - 我应该使用什么 sleep 或定时器

标签 c# timer sleep

我有两种选择使用定时器或使用 sleep ,我需要在这个方法完成后每 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 是线程安全的,它可以帮助我实现我想要实现的行为吗?

谢谢。

最佳答案

您是否意识到 fooUsingSleep 正在一遍又一遍地调用自己?它最终会产生堆栈溢出。

如果你使用定时器,它可以像这样简单:

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

关于c# - 我应该使用什么 sleep 或定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4679539/

相关文章:

c# - 我可以集成到我的 asp.net 项目中的 asp.net c# 论坛软件?

android - Android中带回调函数的通用定时器类

javascript - 我不明白 javascript 中的 setTimeout(fn,0) 是如何工作的

c# - 在分配对象之前引用对象的最佳方法?

c# - 在自动滚动面板上预览鼠标滚轮

c# - Windows Phone 正确显示项目集合的方法

Java:使用带定时器的信号量

c++ - sleep 限制了线程性能

c - sleep 系统调用,默认 sleep 时间是多少?

android - 如何在 sleep 模式下接收硬件按键事件?