When System.Windows.Forms.Timer is used in Winform to start and stop the timer multiple times, the bound event will be executed multiple times.

Scenes

Implementing the timer function in C# (scheduled tasks and how long to wait before executing a method):

Implementing the timer function in C# (scheduled tasks and how long to wait before executing a certain method)_c# timer 5 minutes_Domineering Rogue Temperament Blog-CSDN Blog

The above is about the use of timers.

When I clicked the button to start the timer and clicked the stop button to stop the timer, I found that repeating it multiple times would cause the timer method to be executed repeatedly.

Think of the following situation

Solution to the problem that event subscription is not canceled when the window is closed in C#, causing the event to be executed repeatedly:

Solution to the problem of repeated execution of events when the window is closed without canceling the event subscription in C#_Duplicate binding of events in C#_The blog of domineering and rogue temperament-CSDN blog

So I thought that when stopping the timer, I just simply stopped the execution, and there was no specific method to unbind the timer execution.

Because the Timer is initialized once and is not new every time, it is necessary to unbind the execution method when stopping the timer.

Note:

Blog:
Domineering Rogue Temperament_C#, Architecture Road, SpringBoot-CSDN Blog

accomplish

1. Initialize timer

Timer _timer = new Timer();

Use as class variable

2. Start the timer

_timer.Interval = scheduleInterval;                 
_timer.Tick += _timer_Tick;
_timer.Start();

3. Stop the timer

_timer.Tick -= _timer_Tick;
_timer.Stop();

4. Specific business scenario reference

Timer is implemented in C# to periodically determine whether the IP is pinged (connected) and whether the port number is reachable (available) via telnet:

Implementing a timer in C# to regularly determine whether the IP is pinged (connected) and whether the port number is reachable (available) via telnet_The Blog of Overbearing Rogue Temperament-CSDN Blog

Guess you like

Origin blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/133271648