In this paper, we describe the automatic management of multithreading using Timers for C # multithread learning. Share to everyone for your reference. The specific analysis is as follows:
Timer class: Set a timer to execute the user-specified function on a timed basis.
After the timer starts, a new thread is automatically created to execute the user-specified function.
Initialize a Timer object:
?
1 |
Timer timer = new Timer(timerDelegate, s,1000, 1000); |
First parameter: The TimerCallback delegate is specified, indicating the method to be executed;
Second argument: An object containing the information to be used by the callback method, or a null reference;
Third parameter: Delay time-the time at which the timing starts, in milliseconds, specified as "0", to start the timer immediately;
Fourth parameter: Timer Interval--After the start of the timer, every so long period of time, the method that TimerCallback represents will be called once, the unit is also milliseconds. Specifies that timeout.infinite can disable periodic termination.
Timer.change () Method: Modify the Timer settings. (This is a method of parameter type overloading)
Examples of Use:
?
1 |
timer.Change(1000,2000); |
Example of a program for the Timer class (Source: MSDN):
?
12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
using System;
using System.Threading;
namespace ThreadExample
{
class TimerExampleState
{
public int counter = 0;
public Timer tmr;
}
class App
{
public static void Main()
{
TimerExampleState s =
new TimerExampleState();
//创建代理对象TimerCallback,该代理将被定时调用
TimerCallback timerDelegate =
new TimerCallback(CheckStatus);
//创建一个时间间隔为1s的定时器
Timer timer =
new Timer(timerDelegate, s,1000, 1000);
s.tmr = timer;
//主线程停下来等待Timer对象的终止
while
(s.tmr !=
null
)
Thread.Sleep(0);
Console.WriteLine(
"Timer example done."
);
Console.ReadLine();
}
//下面是被定时调用的方法
static void CheckStatus(Object state)
{
TimerExampleState s =(TimerExampleState)state;
s.counter++;
Console.WriteLine(
"{0} Checking Status {1}."
,DateTime.Now.TimeOfDay, s.counter);
if
(s.counter == 5)
{
//使用Change方法改变了时间间隔
(s.tmr).Change(10000,2000);
Console.WriteLine(
"changed"
);
}
if
(s.counter == 10)
{
Console.WriteLine(
"disposing of timer"
);
s.tmr.Dispose();
s.tmr =
null
;
}
}
}
}
|
The program first creates a timer, which begins to call the CheckStatus () method every 1 seconds after the creation of 1 seconds, and after 5 calls, modifies the time interval to 2 seconds in the CheckStatus () method, and specifies to start again after 10 seconds. When the count reaches 10 times, the call Timer.dispose () method removes the timer object, and the main thread jumps out of the loop and terminates the program.
C # Multithreading Learning (v) automatic multi-threaded management using timers