SoFunction
Updated on 2025-03-07

Timer and DispatcherTimer usage examples in C#

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

The usage is as follows:

Copy the codeThe code is as follows:

class Program {
        static Timer1 = new ();
        static void Main() {
            = 1000;
            += new ElapsedEventHandler(PeriodicTaskHandler);           
            ();
            ();
        }

        static void PeriodicTaskHandler(object sender, ElapsedEventArgs e) {
        string str =()+"##" +"Timer1" +"##" + ();
            (str);
        }
    }

DispatcherTimer: The timer in the Dispatcher queue cannot be guaranteed to execute the timer exactly when the set time interval occurs, but it can be guaranteed not to execute the timer before the time interval occurs. This is because the DispatcherTimer operation is also placed in the Dispatcher queue. When the DispatcherTimer operation is performed depends on other jobs in the queue and their priorities.

In WPF application

Timer's Elapsed event binding method is not run on the UI thread. If you want to access objects on the UI thread, you need to use Invoke or BeginInvoke to publish the operation to the Dispatcher of the UI thread.

The usage is as follows:

Copy the codeThe code is as follows:

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

        }

        void timer_Elapsed(object sender, ElapsedEventArgs e) {
            i++;
            (new Action(() => {
                = ();
            }));
        }

        private int i = 0;

Both the DispatcherTimer and the Dispatcher run on the same thread, and the DispatcherPriority can be set on the DispatcherTimer.

usage

Copy the codeThe code is as follows:

private void Button_Click(object sender, RoutedEventArgs e) {
            = (1000);
            += new EventHandler(timer_Tick);
            ();
        }

        void timer_Tick(object sender, EventArgs e) {
            i++;
            = ();
        }

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