Timer The timer is on the C# Frequently used in development , But many developers don't know him , Today, we will explain it in detail C# Timer in .
stay C# Exist in 3 Common Timer :
* System.Windows.Forms.Timer
* System.Timers.Timer
* System.Threading.Timer
<> Zero ,System.Windows.Forms.Timer
this Timer It's single threaded , That is, as long as it runs , Other threads are waiting .
this Timer It has the following characteristics :
* Completely based on UI thread , When timer is triggered , The operating system inserts timer messages into the thread message queue , The calling thread executes a message pump to extract messages , It is then sent to the callback method Tick in ;
* use Start and Stop start and stopping Timer;
* UI If the operation is too long, it will cause Tick lose ;
* You can use delegates Hook Tick event ;
* The accuracy is not high ;
* Through the Enabled Set to True, send Timer Automatic operation
You can see from the first feature above , The Timer Will cause WinForm UI Feign death , So if you need to process a lot of computation or a lot of time IO Task of operation , This is not recommended Timer
, Let's take a look at an example IO In the case of operation, the situation of suspended animation appears :
We are here Form Put two in Button One Lable And a Timer
private void Button_Click(object sender, EventArgs e) { timer.Interval = 1000;
timer.Tick += Timer_Tick; timer.Start(); } private void Timer_Tick(object sender
, EventArgs e) { for (int i = 0; i < 10000; i++) { File.AppendAllText(Directory.
GetCurrentDirectory()+"test.txt", i.ToString()); this.label_output.Text =
" Current operation : Insert number " + i; } }
We click the calculate button , We'll find out WinForm There was a fake death ( Unable to move window , The button cannot be pressed, etc )
<> One ,System.Timers.Timer
The Timer Is a server based timer , Is designed for use with helper threads in a multithreaded environment , Can be moved between threads to handle raised Elapsed event , More accurate than the last timer .
The Timer It has the following characteristics :
* adopt Elapsed Set fallback handling event , And Elapsed Is running in ThreadPool On the ;
* adopt Interval Set interval time ;
* When AutoReset Set to False Time , Triggered only after the first time interval is reached Elapsed event ;
* Is a multithreaded timer ;
* Cannot be called directly WinForm Controls on , Need to use entrust ;
* Mainly used in Windows In service .
Again, let's take a look at the code Timer How to use the timer : System.Timers.Timer timersTimer = new System.
Timers.Timer(); private void Button_Click(object sender, EventArgs e) {
timersTimer.Interval = 1000; timersTimer.Enabled = true; timersTimer.Elapsed +=
TimersTimer_Elapsed; timersTimer.Start(); } private void TimersTimer_Elapsed(
object sender, System.Timers.ElapsedEventArgs e) { for (int i = 0; i < 10000; i
++) { this.BeginInvoke(new Action(() => { this.label_output.Text=" current time :"+
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); }), null); } } private void
Button1_Click(object sender, EventArgs e) { timersTimer.Stop(); }
Run the code above , You'll find out WinForm The fake interface is gone .
<> Two ,System.Threading.Timer
The Timer It is also a multithreaded timer , It has the following characteristics :
* Multithreading
* Compared with the first two timers, No Start and Stop method , If you want to stop the timer , Must be called Dispose Method to destroy Timer object ;
* call Dispose Method does not immediately stop all timers , This is due to multiple threads running when the interval time is less than the execution time , Multiple threads cannot be stopped at the same time ;
* It's a lightweight timer ;
* All parameters are set in the constructor ;
* Start time can be set ;
* No more WinForm In the program .
Let's take a look at the code ( Enter the following code in the console application ): static System.Threading.Timer threadingTimer;
static int numSum = 0; static void Main(string[] args) { threadingTimer = new
System.Threading.Timer(new System.Threading.TimerCallback(threadingTimer_Elapsed
), null, 0, 1000); Console.Read(); } private static void threadingTimer_Elapsed(
object state) { for (int i = 0; i < 10000; i++) { numSum++; Console.WriteLine(
" Output number :"+i); } if (numSum > 10000) { threadingTimer.Dispose(); Console.WriteLine(
" end "); } }
be careful : When we no longer need multithreading Timer When the timer is on , We can call Dispose
Method to release the occupied resources . But because Timer Timers schedule callback execution by thread pool thread , Therefore, the callback may occur in Dispose After the overload of the method is called , So we can use the
Dispose(WaitHandle) Method to wait for all backdrops to complete .
<> Three , summary
To sum up, we conclude that C# Different from Timer Characteristics and application environment of timer
timer characteristic Environmental Science
System.Windows.Forms.Timer Single thread , be based on UI, The accuracy is not high , Will cause Form Stuck
WinForm development , And there is no need for timing processing IO Operations and massive computing operations
System.Timers.Timer Multithreading , Running in ThreadPool Mainly used for WinSerice development , Used in WinForm You need to call the control on the form through a delegate
System.Threading.Timer Multithreading , Execution in thread pool , Lightweight , Need to pass Dispose stop it , Parameters need to be set in the constructor Not recommended in WinForm Use in
Technology