采用System.Timer,使用Invoke或者BeginInvoke的方式进行UI的更新的方式(好处在于:在DispatcherTimer里面执行等待动作或者时间过长,可能会导致UI假死)
“`
using System;
using System.Windows;
using System.Timers;
using System.Windows.Threading;
namespace TimerTest
{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
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();
}
}
}