zoukankan      html  css  js  c++  java
  • Timer(System.Timers) 和 DispatcherTimer

    Timer组件是基于服务器的计时器,通过设置时间间隔Interval,周期性的触发Elapsed事件。

    用法如下:

        class Program {
    static System.Timers.Timer Timer1 = new System.Timers.Timer();
    static void Main() {
    Timer1.Interval = 1000;
    Timer1.Elapsed += new ElapsedEventHandler(PeriodicTaskHandler);
    Timer1.Start();
    Console.ReadLine();
    }

    static void PeriodicTaskHandler(object sender, ElapsedEventArgs e) {
    string str =Thread.CurrentThread.ManagedThreadId.ToString()+"##" +"Timer1" +"##" + e.SignalTime.ToLongTimeString();
    Console.WriteLine(str);
    }
    }

    DispatcherTimer:Dispatcher队列中的计时器,不能保证正好在设置的时间间隔发生时执行计时器,但能保证不会在时间间隔发生之前执行计时器。这是因为  DispatcherTimer的操作也是放置在Dispatcher队列中的,何时执行DispatcherTimer操作取决于队列中其他作业及其优先级。

    在WPF应用程序中

    Timer的Elapsed事件绑定的方法没有运行在UI线程上,如果要访问UI线程上的对象,需要利用Invoke或BeginInvoke 将操作发布到UI线程的Dispatcher上。

    用法如下

    private void Button_Click(object sender, RoutedEventArgs e) {
    Timer timer = new Timer();
    timer.Interval = 1000;
    timer.Start();
    timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);

    }

    void timer_Elapsed(object sender, ElapsedEventArgs e) {
    i++;
    this.Dispatcher.Invoke(new Action(() => {
    test.Content = i.ToString();
    }));
    }

    private int i = 0;



    DispatcherTimer与Dispatcher都运行于相同的线程,并且可以在DispatcherTimer上设置DispatcherPriority。

    用法

    private void Button_Click(object sender, RoutedEventArgs e) {
    timer.Interval = TimeSpan.FromMilliseconds(1000);
    timer.Tick += new EventHandler(timer_Tick);
    timer.Start();
    }

    void timer_Tick(object sender, EventArgs e) {
    i++;
    Test.Content = i.ToString();
    }

    private int i = 0;
    private DispatcherTimer timer = new DispatcherTimer();

    详细代码:DownLoad

  • 相关阅读:
    Python全栈-第六课 学习笔记
    python基础 day27 装饰器函数classmethod、staticmethod
    python基础 day26 面向对象-super方法、封装、property装饰器、反射
    python基础 day25 面向对象-继承2
    python基础 day24 面向对象-继承1
    python基础 day23 面向对象2
    python基础 day22 面向对象
    python基础 day21 递归函数、shutil模块
    python基础 day20 re模块、带参数的装饰器
    python基础 day19 正则表达式
  • 原文地址:https://www.cnblogs.com/greenteaone/p/2313107.html
Copyright © 2011-2022 走看看