MSDN Timer.Elapsed示例如何在没有用户交互的情况下工作
本文关键字:用户 交互 工作 情况下 Elapsed Timer MSDN | 更新日期: 2023-09-27 18:21:09
至少对我来说,这是使用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);
}
}
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();
}
有几种不同的方法。
这里有一个例子:
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;
}
}
当主线程终止时,应用程序将退出。这是执行Main()的线程。你的计时器将在另一个线程上启动。所以,如果你不想做Console.ReadLine(),基本上你需要做的是Thread.Sleep(5000),其中5000是线程将睡眠的毫秒数。这将使您的主线程等待计时器启动。