The 1.system.threading.timer timer provides a way to repeatedly invoke an asynchronous thread. There are multiple timer classes in the. Net BCL. such as the System.Windows.Forms.Timer class for Windows applications, such as the System.Timers.Timer class that can run on a user interface thread or on a worker thread. They are very different, and the System.Threading.Timer class here is a class that calls an asynchronous thread at regular intervals. Each time the timer is set, the system goes to the thread pool to open a thread to run the provided callback method.
2. The way to invoke this timer class to run the asynchronous thread repeatedly is simple:
Timer MyTimer = new Timer (TimerCallback callback, Object state, uint duetime, uint period);
The parameter in the above method, Duetime is the wait time before the first call to the asynchronous thread, for the whole number of milliseconds, such as 2000, which represents the first call after 2 seconds;
Period is the time interval between two calls, is an integer number of milliseconds, such as 1000, that is called every 1 seconds (that is, an asynchronous thread is initiated, and the newly initiated asynchronous thread does not affect the previously initiated thread, and all the initiated threads continue to execute, as in the following example, until the user closes the program until all threads are finished running. );
State can be null or a reference to the object to pass in each time the asynchronous thread is invoked;
Callback is a parameter that passes in an object type, and the return value is a method of the delegate type of void, which is defined by the user, as in the following example.
3. Program run result (console program)
4. Code
Using System;
Using System.Threading;
Namespace the asynchronous thread repeatedly with a timer
{
class program
{
int timescalled = 0;
void Display (object state)
{
Console.WriteLine (' {0} {1} keep running. ', (string) state, ++timescalled);
}
static void Main ()
{program
p = new program ();
Timer MyTimer = new timer (p.display, "Processing Timer event", 2000, 1000);//2 seconds after the first call, every 1 seconds call
//timer myTimer1 = new T Imer (P.display, "Processing Timer event", Timeout.infinite, 1000);//will never be invoked
//timer MyTimer2 = new Timer (p.display , "Processing Timer event", Timeout.infinite, the first call after 2 seconds, and then call
Console.WriteLine Again ("Timer started.");
Console.ReadLine ();}}