Have fun with sci.dog

C# DispacherTimer 计时器

1. DispacherTimer 是什么?

DispacherTimer在 System.Windows.Threading下定义的类,使用前需要加上:
using System.Windows.Threading;

2. 如何使用 DispacherTimer ?

通过Interval设置计时器的时间间隔,每隔一段固定时间,就执行Tick事件所挂接的用户编写的程序。

    // 设置自动检测事件间隔
   autoDetectionTimer.Interval = new TimeSpan(0, 0, 0, 0, 50);
   // 自动检测时间到->执行事件 挂接函数
   autoDetectionTimer.Tick += new EventHandler(AutoDectionTimer_Tick);
   // 开启定时器
   autoDetectionTimer.Start();
   // 挂接函数: your program here
    private void AutoDectionTimer_Tick(object sender, EventArgs e)
    {
      // your program here....
      // 可以直接更新UI控件
    }
   // .....
   // 关闭定时器
   // autoDetectionTimer.Stop();

3. 与其他C#里的定时器有什么区别?

与System.Timers.Timer() 的主要区别是,DispacherTimer运行在UI线程,可以直接更新UI画面,而其他定时器运行在非UI线程,如需更新UI画面,需要使用this.Dispatcher切换到UI线程后使用Invoke或者BeginInvoke方法更新UI画面。

4. 小贴士: 看懂“类视图”和“对象浏览器”图标

“类视图”和“对象浏览器”图标

赞(0)
未经允许不得转载:SciDog » C# DispacherTimer 计时器

评论 2

  1. #1

    贴个动画效果就更好了!

    Alp5年前 (2019-05-06)回复
    • 缺个轻松做动画的工具呀。嘿嘿

      fx47225年前 (2019-05-06)回复