MSDN Timer.Elapsed示例如何在没有用户交互的情况下工作?

时间:2014-09-09 15:25:51

标签: c# .net console-application

至少对我而言,这是使用System.Timers.Timer的完美示例。唯一的问题是,如果我消除Console.ReadLine(),它将无法工作。在我的情况下,我只想在5秒后显示一条消息,然后控制台将关闭。那就是它。

所以,让我们说我想在没有任何用户互动的情况下显示简单的消息Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime),我怎么能这样做?换句话说,当我点击F5时,我会看到空白的控制台窗口,在5秒内我会看到该消息,然后控制台就会消失。

以下是MSDN的代码:

using System;
using System.Timers;

public class Example
{
    private static Timer aTimer;

    public static void Main()
    {
        // Create a timer with a two second interval.
        aTimer = new System.Timers.Timer(5000);
        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program... ");
        Console.ReadLine();
        Console.WriteLine("Terminating the application...");
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}

3 个答案:

答案 0 :(得分:4)

using System;
using System.Threading;
using System.Timers;
using Timer = System.Timers.Timer;

private static Timer aTimer;
private static ManualResetEventSlim ev = new ManualResetEventSlim(false);

public static void Main()
{
    // Create a timer with a two second interval.
    aTimer = new System.Timers.Timer(5000);
    // Hook up the Elapsed event for the timer. 
    aTimer.Elapsed += OnTimedEvent;
    aTimer.Enabled = true;
    ev.Wait();
}

private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
    Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    ev.Set();
}

答案 1 :(得分:2)

有几种不同的方式。

以下是一个例子:

using System;
using System.Timers;

public class Example
{
   private static Timer aTimer;
   private static bool delayComplete = false;

   public static void Main()
   {
      // Create a timer with a two second interval.
      aTimer = new System.Timers.Timer(5000);
      // Hook up the Elapsed event for the timer. 
      aTimer.Elapsed += OnTimedEvent;
      aTimer.Enabled = true;

      while (!delayComplete)
      {
         System.Threading.Thread.Sleep(100);
      }
   }

   private static void OnTimedEvent(Object source, ElapsedEventArgs e)
   {
      Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
      delayComplete = true;
   }
}

答案 2 :(得分:2)

当主线程终止时,您的应用程序将退出。这是执行Main()的线程。您的计时器将在另一个线程上触发。所以基本上你需要做什么,如果你不想做Console.ReadLine()是Thread.Sleep(5000),其中5000是线程将睡眠的毫秒数。这将使你的主线程等到计时器触发。