System. Threading. Timer is a timer that uses the callback method and serves by the thread pool thread. It is simple and does not require high resources.
"As long as you are using timer, you must keep references to it.
"For any managed object, if there is no reference to timer, the timer will be reclaimed. Timer is recycled even if it is still active.
"When you no longer need a timer, use the dispose method to release the resources held by the timer.
Use the timercallback delegate to specify the method to be executed by the timer. The timer delegate is specified when the timer is constructed and cannot be changed. This method is not executed in the thread that creates the timer, but in the thread pool thread provided by the system.
When creating a timer, you can specify the amount of time (End Time) waiting before the first method is executed and the amount of time (cycle) waiting in the subsequent execution period ). You can use the change method to change these values or disable timers.
Demo Application:
Application Scenario: in Windows formProgramAfter a job is automatically executed, you want its Windows form to be automatically disabled.
"CodeDesign:
(1) Declare the timer variable first:
// Make sure to declare a local variable to keep reference to timer; otherwise, it will be recycled by the garbage collector!
Private system. Threading. Timer timerclose;
(2) Add the following timer instantiation code after the above Automatic Execution Code:
// Create a timer thread and start it
Timerclose = new system. Threading. Timer (New timercallback (timercall), this, 5000, 0 );
// Timer constructor parameter description:
Callback: A timercallback delegate that indicates the method to be executed.
State: an object that contains the information to be used by the callback method, or a null reference (nothing in Visual Basic ).
Duetime: The amount of time delay before calling callback (in milliseconds ). Specify timeout. Infinite to prevent the timer from starting timing. Specify zero (0) to start the timer immediately.
Period: The interval (in milliseconds) between calls to callback ). The specified Timeout. Infinite can disable periodic termination.
(3) define the method to be executed by the timercallback delegate:
Private void timercall (Object OBJ)
{
Timerclose. Dispose ();
This. Close ();
}
Of course, in addition to using the timercallback delegation mechanism of the above system. Threading. Timer class, there should be many other methods.
In addition, it only demonstrates the simple application of the timercallback delegate.
Appendix about the article
When reading a piece of code about design pattern, we can see that the Timer class timercallback delegate is used and recorded along.
Reference:
1, msdn, system. Threading. Timer class
(From: http://hi.baidu.com/murphy1314/blog/item/4c0413b5557c3bc936d3cab9.html)
Recommendation: an instance that understands autoresetevent and manulresetevent usage http://xhinker.blog.51cto.com/640011/180377
AutoreseteventAllows threads to communicate with each other by sending signals. Generally, this communication involves resources that the thread needs to exclusively access.
The thread callsAutoreseteventTo wait for the signal. IfAutoreseteventIf the thread is not terminated, the thread is blocked and waits for the thread to control the resource.
Call set to send a signal that resources are available.
CallSetDirectionAutoreseteventSend a signal to release the waiting thread.AutoreseteventWill remain terminated until a waiting thread is released, and then automatically return non-terminated
Status. If no thread is waiting, the state is permanently terminated.
You can control it by passing a Boolean value to the constructor.AutoreseteventIf the initial status is terminatedTrueOtherwiseFalse.
In general, only after myreseteven. Set () runs successfully will myreseteven. waitone () be able to get the running opportunity; set is a signal, waitone is a waiting signal, and only a signal is sent,
Wait for execution. If it is not sent, the program after waitone will never be executed. Let's take an example: I went to the bookstore to buy books. When I selected a book, I would pay for it at the toll booth,
Pay the money and go to the warehouse to get the book. This order cannot be reversed. I act as the main thread, and there are two auxiliary threads at the toll booth and the warehouse. The Code is as follows:
Using System; Using System. LINQ; Using System. Activities; Using System. Activities. statements; Using System. Threading; Namespace Caryaredemo { Class Me { Const int Numiterations = 550 ; Static Autoresetevent Myresetevent =New Autoresetevent ( False ); Static Autoresetevent Changeevent = New Autoresetevent ( False ); // Static manualresetevent myresetevent = new manualresetevent (false); // static manualresetevent changeevent = new manualresetevent (false ); Static int Number; // This is a key resource Static void Main (){ Thread Paymoneythread = New Thread ( New Threadstart (Paymoneyproc); paymoneythread. Name = "Payment thread" ; Thread Getbookthread = New Thread ( New Threadstart (Getbookproc); getbookthread. Name = "Book picking thread" ; Paymoneythread. Start (); getbookthread. Start (); For ( Int I = 1 ; I <= numiterations; I ++ ){ Console . Writeline ( "Book buying thread: quantity {0 }" , I); number = I; // Signal that a value has been written. Myresetevent. Set (); changeevent. Set (); Thread . Sleep ( 0 );} Paymoneythread. Abort (); getbookthread. Abort ();}Static void Paymoneyproc (){ While ( True ) {Myresetevent. waitone (); // Myresetevent. Reset (); Console . Writeline ( "{0}: quantity {1 }" , Thread . Currentthread. Name, number );}} Static void Getbookproc (){ While ( True ) {Changeevent. waitone ();// Changeevent. Reset (); Console . Writeline ( "{0}: quantity {1 }" , Thread . Currentthread. Name, number ); Console . Writeline ( "------------------------------------------" ); Thread . Sleep ( 0 ) ;}}} The running result is as follows:
Autoresetevent and manualresetevent
Their usage and declaration are similar. The set method sets the signal to the sending status reset method and sets the signal to the non-sending status waitone waiting for the signal to be sent. In fact, we can see from the name that a manual,
An automatic method. manual and automatic actually refer to the reset method processing, as shown in the following example:
Public autoresetevent autoevent = new autoresetevent (true );
Public manualresetevent manualevent = new manualresetevent (true );
All signals are sent by default,
Autoevent. waitone ();
Manualevent. waitone ();
If a thread calls the above method, when the signal is in the sending status, the thread will receive a signal to continue execution. After the difference is called, autoevent. waitone () allows only one thread at a time.
When a thread gets a signal (that is, other threads call autoevent. after the Set () method), autoevent automatically sets the signal to not sent, and other threads that call waitone only
Wait. That is, autoevent only wakes up one thread at a time. Manualevent can wake up multiple threads, because when a thread calls the set method, other threads that call waitone
The obtained signal can be continued, while manualevent does not automatically set the signal to not be sent. that is, unless manualevent is manually called. reset (). method, manualevent will remain in the signal state, and manualevent will be able to wake up multiple threads at the same time to continue execution. If the preceding program is replaced with manualresetevent, You need to reset it after waitone.
From: http://www.cnblogs.com/carysun/archive/2009/10/29/autoresetevent.html
Today, when I read a Demo code, I found that autoresetevent was used repeatedly. I checked the information in msnd and found a very short example on the Internet, this example has helped me understand the usage of autoresetevent and has played a lot of auxiliary functions. It is posted here, hoping to help you understand it:
(The code has been successfully debugged in vs2005. Comments are my understanding and can only serve as a reference)
Using system;
Using system. Threading;
Namespace autoresetevent_examples
{
Class mymainclass
{
// There is no signal at the beginning, which means that the parameter is false.
Const int numiterations = 100; // It doesn't matter how many repeated times are set. It sets 100 for you to see clearly.
Static autoresetevent myresetevent = new autoresetevent (false );
Static int number;
static void main ()
{< br> // create and start a thread.
thread myreaderthread = new thread (New threadstart (myreadthreadproc);
myreaderthread. Name = "readerthread";
myreaderthread. Start ();
For (INT I = 1; I <= numiterations; I ++)
{
Console. writeline ("writer thread writing value: {0}", I );
Number = I;
// Sends a signal, indicating that the value has been written into it. Set is a method for sending signals.
Myresetevent. Set ();
// Make some intervals in each loop, which has no other effect and can be commented out.
Thread. Sleep (1000 );
}
// Terminate the reading thread.
Myreaderthread. Abort ();
}
static void myreadthreadproc ()
{< br> while (true)
{
// The data is not read by the reader until it is written by the author
// at least once before the last read.
myresetevent. waitone ();
console. writeline ("{0} reading value: {1}", thread. currentthread. name, number);
}< BR >}
I will describe it in the diagram below to make it easier for everyone to understand. Before using autoresetevent, you must perform initialization through examples, for example:
Autoresetevent myresetevent = new autoresetevent (false );
As mentioned in msdn, to set the initial state to terminationTrueIf you want to set the initial status to non-terminatedFalse
Women's understanding: If this parameter is set to true, that is, this event is returned to automatic reset, then myresetevent. waitone () will be able to get the running right when the program starts; it is equivalent to automatically running myreseteven once the program starts. set ();
Otherwise, it is necessary to wait until myreseteven. Set () runs successfully before myreseteven. waitone () can get the running opportunity;
Here I will make an experiment for you to see that when set to true, we will first see the readerthread reading value running, and then the writer thread wrirting:
If it is set to false, you will find that the write information first appears:
I believe everyone should understand its initial meaning.
The above mentioned myreseteven. set (). What does this method do? Simply put, it is equivalent to a switch. If the Set () method is not executed, the following waitone () so that the statements after waitone will not be executed, and waitone () will be silly... the operation after set () is executed will not be executed until it is executed,
Let's try again and comment out myreseteven. Set (). The result is that the read information will never appear ,:
As we expected, only the written information is executed.
In combination, autoresetevent provides a toggle similar to condition judgment to control the thread,
If ()
{
......
}
That is to say, if the thread above autoresetevent. Set () is fully executed, the thread under the control of autoresetevent. waitone () will be executed. It's easy !!
I don't know if the female's expression is clear. If you have any questions, please contact us!
From: http://hi.baidu.com/iaskall/blog/item/1938e00045f87012738b6526.html
AutoreseteventAllows threads to communicate with each other by sending signals. Generally, this communication involves resources that the thread needs to exclusively access.
The thread callsAutoreseteventTo wait for the signal. IfAutoreseteventIf the thread is not terminated, the thread is blocked and waits for the thread to control the resource.
Call set to send a signal that resources are available.
CallSetDirectionAutoreseteventSend a signal to release the waiting thread.AutoreseteventWill remain terminated until a waiting thread is released, and then automatically return non-terminated
Status. If no thread is waiting, the state is permanently terminated.
You can control it by passing a Boolean value to the constructor.AutoreseteventIf the initial status is terminatedTrueOtherwiseFalse.
In general, only after myreseteven. Set () runs successfully will myreseteven. waitone () be able to get the running opportunity; set is a signal, waitone is a waiting signal, and only a signal is sent,
Wait for execution. If it is not sent, the program after waitone will never be executed. Let's take an example: I went to the bookstore to buy books. When I selected a book, I would pay for it at the toll booth,
Pay the money and go to the warehouse to get the book. This order cannot be reversed. I act as the main thread, and there are two auxiliary threads at the toll booth and the warehouse. The Code is as follows:
Using System; Using System. LINQ; Using System. Activities; Using System. Activities. statements; Using System. Threading; Namespace Caryaredemo { Class Me { Const int Numiterations = 550 ; Static Autoresetevent Myresetevent = New Autoresetevent ( False ); Static Autoresetevent Changeevent = New Autoresetevent ( False );// Static manualresetevent myresetevent = new manualresetevent (false); // static manualresetevent changeevent = new manualresetevent (false ); Static int Number; // This is a key resource Static void Main (){ Thread Paymoneythread = New Thread ( New Threadstart (Paymoneyproc); paymoneythread. Name = "Payment thread" ; Thread Getbookthread = New Thread ( New Threadstart (Getbookproc); getbookthread. Name = "Book picking thread" ; Paymoneythread. Start (); getbookthread. Start (); For ( Int I = 1 ; I <= numiterations; I ++ ){ Console . Writeline ( "Book buying thread: quantity {0 }" , I); number = I;// Signal that a value has been written. Myresetevent. Set (); changeevent. Set (); Thread . Sleep ( 0 );} Paymoneythread. Abort (); getbookthread. Abort ();} Static void Paymoneyproc (){ While ( True ) {Myresetevent. waitone (); // Myresetevent. Reset (); Console . Writeline ( "{0}: quantity {1 }" ,Thread . Currentthread. Name, number );}} Static void Getbookproc (){ While ( True ) {Changeevent. waitone (); // Changeevent. Reset (); Console . Writeline ( "{0}: quantity {1 }" , Thread . Currentthread. Name, number ); Console . Writeline ( "------------------------------------------" ); Thread . Sleep ( 0 ) ;}}} The running result is as follows:
Autoresetevent and manualresetevent
Their usage and declaration are similar. The set method sets the signal to the sending status reset method and sets the signal to the non-sending status waitone waiting for the signal to be sent. In fact, we can see from the name that a manual,
An automatic method. manual and automatic actually refer to the reset method processing, as shown in the following example:
Public autoresetevent autoevent = new autoresetevent (true );
Public manualresetevent manualevent = new manualresetevent (true );
All signals are sent by default,
Autoevent. waitone ();
Manualevent. waitone ();
If a thread calls the above method, when the signal is in the sending status, the thread will receive a signal to continue execution. After the difference is called, autoevent. waitone () allows only one thread at a time.
When a thread gets a signal (that is, other threads call autoevent. after the Set () method), autoevent automatically sets the signal to not sent, and other threads that call waitone only
Wait. That is, autoevent only wakes up one thread at a time. Manualevent can wake up multiple threads, because when a thread calls the set method, other threads that call waitone
The obtained signal can be continued, while manualevent does not automatically set the signal to not be sent. that is, unless manualevent is manually called. reset (). method, manualevent will remain in the signal state, and manualevent will be able to wake up multiple threads at the same time to continue execution. If the preceding program is replaced with manualresetevent, You need to reset it after waitone.