If you need to repeat some methods at regular intervals, the easiest way to do this is to use Timer (timer). Compared to the example below, timers can use memory and resources efficiently and easily:
New Thread (Delegate () {while
(enabled)
{
dosomeaction ();
Thread.Sleep (timespan.fromhours);
}
). Start ();
Not only does this permanently take up a thread, but if there is no additional code, dosomeaction occurs later in the day. The timer solves these problems.
The. NET Framework provides 4 kinds of timers. The bottom two classes are generic multithreaded timers:
(1) System.Threading.Timer
(2) System.Timers.Timer
The other two are dedicated single-threaded timers:
(3) System.Windows.Forms.Timer (Windows Forms timer)
(4) System.Windows.Threading.DispatcherTimer (WPF timer)
Multithreaded timers are more powerful, accurate, and flexible, while single-threaded timers are safe and convenient for some simple tasks that update Windows Forms and WPF controls.
1. Multithreading Timer permalink
System.Threading.Timer is the simplest multithreaded timer: it has only one construction method and two common methods (pleasing to the minimalist, and the author of the book!). )。 In the next example, a timer calls the Tick method after 5 seconds to print "tick ..." , and then print once per second until the user presses the ENTER key:
Using System;
Using System.Threading;
Class program
{
static void Main ()
{
//First interval 5000ms, after 1000ms
Timer TMR = new Timer (Tick, "Tick ...") , 5000, 1000);
Console.ReadLine ();
Tmr. Dispose (); Stop the timer and perform cleanup work
} The
static void Tick (object data)
{
//is run on a thread pool threads
Console.WriteLine (data) ; Print "Tick ..."
}
You can then change the time interval of the timer by calling the changes method. If you want the timer to be triggered only once, you can specify Timeout.infinite as the last argument to construct the method.
The. NET Framework provides another timer class with the same name under the System.Timers namespace. It simply encapsulates the System.Threading.Timer and provides additional convenience with the exact same underlying engine. Here is an introduction to adding features:
(1) Implements the component and allows it to be used in Visual Studio's designer.
(2) The Interval property replaces the change method.
(3) The elapsed event replaces the callback delegate.
(4) The Enabled property is used to start or stop the timer (the default value is False).
(5) Start and stop methods to avoid confusion with the Enabled property.
(6) The Autoreset identity to specify whether it is a repeatable event (the default is true).
The SynchronizingObject property provides the Invoke and BeginInvoke methods that are used to safely invoke methods on WPF and Windows Forms controls.
Here's an example:
Using System;
Using System.Timers; The namespace is timers instead of Threading
class Systemtimer
{
static void Main ()
{
Timer TMR = new timer (); No parameter
TMR required. Interval = +;
Tmr. Elapsed + = tmr_elapsed; Use events instead of Delegate
TMR. Start (); Open Timer
console.readline ();
Tmr. Stop (); Stop timer
console.readline ();
Tmr. Start (); Restart Timer
console.readline ();
Tmr. Dispose (); Permanent Stop timer
}
static void Tmr_elapsed (object sender, EventArgs e)
{
Console.WriteLine ("Tick");
}
}
Multithreaded timers use line pool to allow a small number of threads to service multiple timers. This means that the callback method or elapsed event may be triggered on a different thread each time. In addition, elapsed always fires almost on time, regardless of whether the previous elapsed completes execution. Therefore, the callback method or event handler must be thread-safe.
The precision of a multithreaded timer depends on the operating system, usually in the 10-20 Ms Range. If higher precision is required, you can use local interop (native interop) to invoke the Windows multimedia timer, which can be improved to 1 Ms. It is defined in Winmm.dll, first call Timebeginperiod to notify the operating system that you need a higher timer precision, and then call timeSetEvent to start the multimedia timer. When the use is complete, call the Timekillevent stop timer, and finally call Timeendperiod to notify the operating system that you are not in need of a higher timer precision. You can find complete examples on the web by searching the keyword dllimport winmm.dll timesetevent.
2. Single-Thread timer permalink
The. NET Framework provides two timers designed to eliminate thread-safety issues for WPF and Windows Forms applications:
System.Windows.Threading.DispatcherTimer (WPF)
System.Windows.Forms.Timer (Windows Forms)
Single-threaded timers are not designed to work outside their specific environment. For example, if you use the Windows Forms Timer in a Windows system service application, the timer event does not fire!
They expose members like System.Timers.Timer (Interval, Tick, start, and stop) and are similar in usage. But the difference is how the interior works. Instead of using line pool to generate timer events, WPF and the Windows Forms timer depend on the underlying message loop mechanism of the UI model (messages pumping mechanism). means that the tick event is always triggered by the thread that created the timer, in the usual program, which is the thread that manages all UI elements and controls. This has many advantages:
Single-threaded timers are more secure and easier to update for simple tasks such as Windows Forms controls or WPF. A SynchronizingObject object that invokes a method securely in WPF or Windows Forms.
Single-threaded timers are timers that are designed to be part of their execution environment, and if you use Windows Forms in a Windows service application, the Timer,timer event will not be triggered and will only be triggered in the corresponding environment.
Like System.Timers.Timer, they also provide the same members (Interval,tick,start,stop), but their internal working principles are different, and WPF and Windows The forms timer uses the message loop mechanism to replace the thread pool's mechanism for generating messages.
You may not have to consider thread safety.
The new tick is not triggered until the previous tick completes execution.
You can update the UI control directly in the processing code of the tick time event without having to call Control.Invoke or Dispatcher.invoke.
It sounds incredibly good until you realize that the program using these timers is not really multithreaded and will not execute in parallel. One thread serves all timers and also handles UI events. This brings a single thread timer's disadvantage:
The UI will lose its response unless the Tick event handler executes quickly.
This makes WPF and Windows Forms timers available only for small tasks, usually those that update the appearance of the UI (for example, display a clock or countdown). Otherwise, you'll need a multithreaded timer.
In terms of precision, single-threaded timers are similar to multi-threaded timers (dozens of milliseconds), but are usually less accurate because they are deferred by other UI requests (or other timer events).
The single-threaded timer is based on the Windows message loop, and the application synchronizes the messages that process the timer. You will find that the UI interface is slower than the corresponding speed. The way to solve this problem is to use a multithreaded timer.
The disadvantage of a single-threaded timer: Unless the processing code for the Tick event executes very quickly, the UI interface becomes slow to respond. So the timers for WPF and Windows Forms are ideal for small tasks, especially for interface updates. For example clocks and counting displays. Otherwise, you need a multithreaded timer