DispatcherTimer 未触发 Tick 事件
我有一个像这样初始化的 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 事件永远不会被触发,我错过了什么吗?
I have a DispatcherTimer i have initialised like so:
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
}
The _timer_Tick event never gets fired, have i missed something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果这是您的主入口点,则很可能(几乎可以肯定)
Main
方法会在第一个DispatcherTimer
事件发生之前退出。一旦 Main 完成,该进程就会关闭,因为没有其他前台线程。
话虽如此,
DispatcherTimer
实际上仅在拥有Dispatcher
的用例(例如 WPF 或 Silverlight 应用程序)中才有意义。对于控制台模式应用程序,您应该考虑使用 Timer 类,即:If this is your main entry point, it's likely (near certain) that the
Main
method exits prior to when the firstDispatcherTimer
event could ever occur.As soon as Main finishes, the process will shut down, as there are no other foreground threads.
That being said,
DispatcherTimer
really only makes sense in a use case where you have aDispatcher
, such as a WPF or Silverlight application. For a console mode application, you should consider using the Timer class, ie:因为主方法线程在调用tick之前就结束了。
because the main method thread ended before the tick was called.
你错过了Application.Run()。如果没有调度程序循环,则无法调度 Tick 事件。第二个问题是您的程序在引发事件之前立即终止。 Application.Run() 也解决了这个问题,它阻塞了 Main() 方法。
You missed Application.Run(). Tick events cannot be dispatched without the dispatcher loop. A secondary issue is that your program immediately terminates before the event ever could be raised. Application.Run() solves that too, it blocks the Main() method.
如果计时器是在工作线程中创建的,则
Tick
事件将不会触发,因为没有调度程序。您必须在 UI 线程中创建计时器或使用 DispatcherTimer 构造函数,该构造函数将 Dispatcher 实例作为第二个参数,并传递 UI 调度程序:
If the timer is created in a worker thread, the
Tick
event will not fire because there is not dispatcher.You have to create the timer in the UI thread or use the
DispatcherTimer
constructor which takes aDispatcher
instance as the second argument, passing the UI dispatcher:您必须启动调度程序才能让调度程序“执行”任何事件。如果您在 WPF 应用程序内部运行,这应该会自动发生。如果您在控制台中运行(看起来像),则永远不会触发,因为没有调度程序。您可以做的最简单的事情就是在 WPF 应用程序中尝试此操作,它应该可以正常工作。
You have to start a dispatcher in order for the dispatcher to "do" any events. If you are running inside of a WPF application, this should happen automatically. If you are running in a console (which it looks like), this will never fire because there isn't a dispatcher. The easiest thing you can do is try this in a WPF application and it should work fine.
你必须
在timer_tick事件的地方使用
You have to use
in the place of timer_tick event