In C#, timers are a common mechanism that can periodically execute a task or event. Common timers include and , which are different in use, but they can all meet the basic timing functions.
However, in some scenarios, we need to use advanced usage of timers to meet higher requirements. For example, a timer with very little resource occupancy and extremely high accuracy is required to avoid performance problems under high load conditions, or the execution time of the timer is required to accurately control the accuracy and stability of the task.
The following are some advanced usages of timers in C#, which can help us realize timers that occupy very little resources and have extremely high accuracy.
Use and ManualResetEventSlim
It is a lightweight timer that can set callback functions and time intervals. To occupy less resources, you can use ManualResetEventSlim to synchronize the callback function.
The specific implementation method is as follows:
private static Timer _timer; private static ManualResetEventSlim _resetEvent; public static void StartTimer(TimeSpan interval, Action action) { _resetEvent = new ManualResetEventSlim(false); _timer = new Timer(state => action(), null, , interval); } public static void StopTimer() { _resetEvent.Set(); _timer.Dispose(); } public static void Wait() { _resetEvent.Wait(); }
When in use, you can call the StartTimer method to start the timer, call the StopTimer method to stop the timer, and call the Wait method to wait for the timer to complete execution. In the callback function, if IO operations or CPU-intensive calculations are required, you can use asynchronous methods or hand over the tasks to the thread pool to avoid blocking the main thread.
Using Stopwatch and Sleep methods
Stopwatch is a high-precision timer that can be used to measure time intervals. The Sleep method can pause the current thread for a certain time. Using these two methods combines to achieve a timer with extremely high accuracy.
The specific implementation method is as follows:
public static void Sleep(TimeSpan interval, Action action) { var sw = (); while ( < interval) { (1); } action(); }
When in use, the Sleep method can be called to wait for the specified time interval and then the callback function can be executed. In the callback function, attention should also be paid to prevent blocking the main thread.
Use and async/await
It is an asynchronous waiting method that can be used to pause the current task for a certain period of time. Using async/await in conjunction with it, you can implement asynchronous and less resource-consuming timers.
The specific implementation method is as follows:
public static async Task Delay(TimeSpan interval, Func<Task> func) { while (true) { await (interval); await func(); } }
Another way is to use the ThreadPoolTimer class. ThreadPoolTimer is part of the WinRT API, which provides a lightweight way to create periodic timers. ThreadPoolTimer consumes less resources than DispatcherTimer and can continue to work when the application hangs.
The ThreadPoolTimer class provides two ways to create: one is to use the CreatePeriodicTimer method to create a periodic timer, and the other is to use the CreateTimer method to create a one-time timer.
Here is a sample code for creating a periodic timer using ThreadPoolTimer:
using ; public class MyTimer { private ThreadPoolTimer timer; public MyTimer() { // Create a periodic timer, triggering every 1 second timer = (TimerElapsedHandler, (1)); } private void TimerElapsedHandler(ThreadPoolTimer source) { // Code executed after the timer expires } }
Note that the TimerElapsedHandler callback method of ThreadPoolTimer runs on a separate thread, so you need to pay attention to thread safety.
In addition to the above two methods, there are some other timer implementation methods, such as Multimedia Timer based on Windows API, and C#-based timer library. These methods have their own advantages and disadvantages. Choosing a suitable timer implementation method requires evaluation based on the specific application scenario.
Therefore, there are many ways to achieve efficient and accurate timers in C#. When choosing the implementation method of the timer, it is necessary to consider factors such as the accuracy of the timer, resource usage, and whether the application can continue to work after it is suspended, and evaluate it according to the specific application scenario.
This is the end of this article about the detailed explanation of the use of various efficient timer methods in C#. For more related C# timer content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!