我该怎么用Sleep或Timer

Del*_*ate 6 c# sleep timer

我有两个使用计时器或使用睡眠的替代方案,我需要在这个方法完成后每隔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();
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是

1)我可以用更优雅的定时器编写代码吗?意味着从fooUsingTimer中删除对callToMethodAfterInterval方法的调用,使计时器为一行或两行,并从fooUsingTimer的声明中删除虚拟变量?

2)我理解睡眠不忙等待(http://www.codeproject.com/KB/threads/ThreadingDotNet.aspx)所以我没有找到在这里使用计时器选项的理由,因为睡眠更简单,什么是更好的使用,计时器版本或睡眠?

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

谢谢.

Hen*_*man 2

程序的真实背景也很重要。

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

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

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

        Console.ReadLine();
    }
Run Code Online (Sandbox Code Playgroud)