Timer和DispatcherTimer简单使用

1. 设定计时器相关属性,使用委托方法处理事件触发

DispatcherTimer dispatcherTimer= new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, _heartBeat.Period);
dispatcherTimer.Start();

 

2.一种比较安全的使用方法

private Timer aTimer = null;
private delegate void TimerDispatcherDelegate();
public MainWindow() {
InitializeComponent();
aTimer = new Timer(1000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 1000;
aTimer.Enabled = true;
}
private void OnTimedEvent(object sender, EventArgs e) {
this.Dispatcher.Invoke(DispatcherPriority.Normal, new TimerDispatcherDelegate(updateUI));
}

private void updateUI() {
timeLabel.Content = DateTime.Now.ToUniversalTime();
}
}

posted @ 2017-09-12 13:47  风来风往风伤(TiAmo)  阅读(1384)  评论(0编辑  收藏  举报