我有一个 DispatcherTimer,我已经像这样初始化了:
static DispatcherTimer _timer = new DispatcherTimer();
static void Main()
{
_timer.Interval = new TimeSpan(0, 0, 5);
_timer.Tick += new EventHandler(_timer_Tick);
_timer.Start();
}
static void _timer_Tick(object sender, EventArgs e)
{
//do something
}
_timer_Tick 事件从未被触发,我是不是错过了什么?
最佳答案
如果这是您的主要入口点,很可能(几乎可以肯定)Main
方法在第一个 DispatcherTimer
事件可能发生之前退出。
一旦 Main 完成,进程将关闭,因为没有其他前台线程。
也就是说,DispatcherTimer
实际上只在您拥有 Dispatcher
的用例中才有意义,例如 WPF 或 Silverlight 应用程序。对于控制台模式应用程序,您应该考虑使用 Timer class ,即:
static System.Timers.Timer _timer = new System.Timers.Timer();
static void Main()
{
_timer.Interval = 5000;
_timer.Elapsed += _timer_Tick;
_timer.Enabled = true;
Console.WriteLine("Press any key to exit...");
Console.ReadKey(); // Block until you hit a key to prevent shutdown
}
static void _timer_Tick(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Timer Elapsed!");
}
关于c# - DispatcherTimer 未触发 Tick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5393810/