DispatcherTimer不会触发Tick事件

har*_*ers 14 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
}
Run Code Online (Sandbox Code Playgroud)

_timer_Tick事件永远不会被解雇,我错过了什么吗?

Ree*_*sey 30

如果这是您的主要切入点,则可能(接近确定)该Main方法在第一个DispatcherTimer事件发生之前退出.

Main完成后,该进程将立即关闭,因为没有其他前台线程.

话虽这么说,DispatcherTimer实际上只有在你有一个Dispatcher例如WPF或Silverlight应用程序的用例中才有意义.对于控制台模式应用程序,您应该考虑使用Timer类,即:

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!");
}
Run Code Online (Sandbox Code Playgroud)


小智 5

因为主方法线程在调用tick之前结束.


Han*_*ant 5

你错过了 Application.Run()。如果没有调度程序循环,就无法调度 Tick 事件。次要问题是您的程序会在事件发生之前立即终止。Application.Run() 也解决了这个问题,它阻塞了 Main() 方法。