Timer and DispatcherTimer use instances in C

  • 2020-12-18 01:54:02
  • OfStack

The Timer component is a server-based timer that periodically triggers Elapsed events by setting the Interval interval.

Usage is as follows:


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: Timers in the Dispatcher queue, which are not guaranteed to be executed exactly when the set time interval occurs, but are guaranteed not to be executed before the time interval. This is because DispatcherTimer's operations are also placed in the Dispatcher queue, and when DispatcherTimer operations are performed depends on the other jobs in the queue and their priority.

In the WPF application

The Elapsed event binding method for Timer does not run on the UI thread, and if you want to access an object on the UI thread, you need to use Invoke or BeginInvoke to publish the operation to Dispatcher on the UI thread.

Usage is as follows:


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 and Dispatcher both run on the same thread, and DispatcherPriority can be set on DispatcherTimer.

usage


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();


Related articles: