Scenes
Implementing the timer function in C# (scheduled tasks and how long to wait before executing a method):
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:
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: