WPF专属计时器

来源:互联网 发布:mysql实时同步数据库 编辑:程序博客网 时间:2024/04/27 22:07

最新在用WPF开发一个小程序,其中需要用到计时器,由于本人第一次接触WPF也就靠着WinForm的经验摸索着写出点东西。

但是在碰到需要用计时器时碰到一个问题,其实也不是什么难点。

原本一直用的是System.Threading.Timer、System.Timers.Timer或是WinForm自带的Timer计时器,但前两个的触发事件如果用来改变UI可能会发生对象被占用的情况。

原因是这两个触发事件和UI不是同线程的,而WinForm自带的Timer计时器在我引用了System.Windows.Forms.Timer之后在WPF中也可以使用,

我想MS应该会为WPF也定制一个计时器吧,于是在网上一搜果然有,在引用了System.Windows.Threading之后就可以添加DispatcherTimer这个计时器,

当然在WPF程序中能用该计时器最好,下面是简单的例子:

private void Window_loaded(object sender,RoutedEventArgs e)
(
DispatcherTimer timer =new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(1000);
timer.Tick += new EventHandler(timer_Tick)
timer.Start();
)
 
void timer_Tick(object sender,EventArgs e)
{
//你的业务
}