c# - DispatcherTimer 未触发 Tick 事件

标签 c# dispatchertimer

我有一个 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/

相关文章:

c# - DispatcherTimer 在 Win 2k8 SP2 中的 Stop() 后继续触发

c# - 更改特定行的颜色 (TELERIK)

c# - 在 MS SQL 2012 上从 Windows Installer 运行 SQL 脚本

c# - 从 List<string[]> 中获取唯一字符串的计数到字典中

c# - 带有参数和 STDOUT 重定向的 Windows 任务计划程序作业

C# 方法隐藏

.net - 一个应用程序中有更多 DispatcherTimers

c# - 执行 ReportProgress 时,BackgroundWorker 或(Dispatcher)操作已完成

c# - 如何使用 dispatchertimer 每 30 秒检查一次而不影响 c# 中的 UI?