今天学习一下多线程在网络上看到一个很好的例子,简单而且很好理解。
1
namespace ThreadTest2


{3
using System;4
using System.Threading;5
class TimerExampleState6

{7
public int counter = 0;8
public Timer tmr;9
}10
class App11

{12
public static void Main()13

{14
TimerExampleState s = new TimerExampleState();15

16
//创建代理对象TimerCallback,该代理将被定时调用17
TimerCallback timerDelegate = new TimerCallback(CheckStatus);18

19
//创建一个时间间隔为1s的定时器20
Timer timer = new Timer(timerDelegate, s, 1000, 1000);//在超过 dueTime 后及此后每隔 period 时间间隔,都会调用一次由 callback 参数指定的委托。21
s.tmr = timer;22

23
//主线程停下来等待Timer对象的终止24
while (s.tmr != null)25

{26
Thread.Sleep(0);27
}28
Console.WriteLine("Timer example done.");29
Console.ReadLine();30
}31
//file://下面是被定时调用的方法32

33
static void CheckStatus(Object state)34

{35
TimerExampleState s = (TimerExampleState)state;36
s.counter++;37
Console.WriteLine("{0} Checking Status {1}.", DateTime.Now.TimeOfDay, s.counter);38
if (s.counter == 5)39

{40
file://使用Change方法改变了时间间隔41
(s.tmr).Change(10000, 2000);42
Console.WriteLine("changed
");43
}44
if (s.counter == 10)45

{46
Console.WriteLine("disposing of timer
");47
s.tmr.Dispose();48
s.tmr = null;49
}50
}51
}52
}53
