DispatcherTimer
此类执行方法跟UI处于同一个线程
private void StartTimer()
{
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += OnTimerHandler;
dispatcherTimer.Interval = new TimeSpan(0, 0, 0,0,100);//每100毫秒刷新一次
dispatcherTimer.Start();
}
private void OnTimerHandler(object sender,EventArgs e)
{
string strTime = DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second + ":" + DateTime.Now.Millisecond;
lbTime.Content = strTime;
}
System.Timers.Timer
此类会另起一个线程,所以当操作UI控件的时候需要注意。
public partial class TimerWindow : Window
{
System.Timers.Timer _timer = new System.Timers.Timer(1000);//设置时间间隔 毫秒
public TimerWindow()
{
InitializeComponent();
_timer.Elapsed += OnTimerHandler;
_timer.AutoReset = true;// false只触发一次 true重复触发
}
private void OnStart()
{
_timer.Start();
}
private void OnStop()
{
_timer.Stop();
}
private void OnTimerHandler(object sender, System.Timers.ElapsedEventArgs e)
{
//需要注意Time类和UI不在同一个线程问题
string strTime = DateTime.Now.ToLongTimeString();
Action cb = delegate () {
lbTime.Content = strTime;
};
this.Dispatcher.Invoke(cb);
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
OnStart();
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
OnStop();
}
}
