SoFunction
Updated on 2025-03-07

The difference and usage of the four C# timer timer

1. Thread timer

1. The lowest level, lightweight timer. Implemented based on thread pool, work in auxiliary threads.

2. It is not internal thread-safe and is more troublesome to use than other timers. This timer is not usually suitable for Windows Forms environments.

Constructor: public Timer(TimerCallback callback, object state, int dueTime, int period);

string state=”.”;
//The state parameter can be passed into the object that you want to process in the callback delegation.  An AutoRestEvent can be passed to send a signal to the main function in the callback function.Timer timer=new Timer(TimeMethod,state,100,1000)//100 indicates how long it will take to start, and 1000 indicates how often it will be executed.
void TimerMethod(object state)
{(());}

();//Canceltimerimplement

2. Server timer

1. The server-oriented service program is based on, designed and optimized to be used in a multi-threaded environment. In this case, you should make sure that the event handler does not interact with the UI. It is generally used in the

2. Inherited from Compnent, it exposes the SynchronizingObject property, avoiding the problem of not being able to access components in the main thread in the thread pool (simulating single-threaded mode). However, unless more precise control of the timing of the event is required, it should still be used instead.

3. The AutoReset property sets whether the timer retimes after the Elapsed event is raised, and the default is true. If this property is set to False, the timer_Elapsed method is executed only once.

4. It is a multi-threaded timer. If a Timer is not processed and reaches the next time point, the new Timer will also be started. Therefore, Timer is more suitable for performing small tasks that are not too time-consuming. If you run time-consuming tasks in Timer, it is easy to have multi-thread reentry problems caused by timeout, that is, multiple threads enter the timer_Elapsed method at the same time.

 timer = new ();
 = 500;
 = this;

+=new (timer_Elapsed);

(); private void timer_Elapsed(Object source,  e)
{
     = value;
}

5. In order to deal with the problem of multi-threaded reentry. Can be locked or flags can be added. Provides a lightweight thread-safe method to assign values ​​to objects, so assign values ​​to variables.

int inTimer = 0;
        void timer_Elapsed(object sender,  e)
        {
            if ((ref inTimer, 1) == 0)
            {
                (3000);
                string currentThreadId = ();
                (new Action(() =>
                {
                    this.Label_Result.Content += currentThreadId + ",";
                }), null);
                (ref inTimer, 0);
            }
        }

3. Windows timer

This timer is directly inherited from Component, which has been specially optimized for use with Windows forms and must be used in windows.

  • The Windows timer is built to run on a message-based UI thread with a precision limited to 5ms. The events executed in the Tick event are the same thread as the main form (single thread) and are safe to interact with the UI.
  • There are only two properties Enable and Internal and a Tick event. The Enable attribute can be controlled using the Start() and Stop() methods.
using ;

public Form1()
{
    InitializeComponent();
     += delegate
    {
        Timer timer = new Timer();
         = 500;
         += delegate
        {
            ($"Timer Thread: {}");
            ($"Is Thread Pool: {}");
             = ();
        };

        ();
        ($"Main Thread: {}");
    };
}

4.

Mainly used in WPF. Properties and methods are similar. The execution of the Tick event in the DispatcherTimer is performed in the main thread.

There is a thing to note when using DispatcherTimer, because the Tick event of the DispatcherTimer is ranked in the Dispatcher queue. When the system is under high load, it cannot be guaranteed to execute in the Interval time period, and there may be slight delays, but it can definitely be guaranteed that the execution of the Tick will not be earlier than the time set by the Interval. If the execution time of Tick is high, you can set the priority of the DispatcherTimer.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.