timer类:设置一个定时器,定时执行用户指定的函数。
定时器启动后,系统将自动建立一个新的线程,执行用户指定的函数。
初始化一个timer对象:
timer timer = new timer(timerdelegate, s,1000, 1000);
// 第一个参数:指定了timercallback 委托,表示要执行的方法;
// 第二个参数:一个包含回调方法要使用的信息的对象,或者为空引用;
// 第三个参数:延迟时间——计时开始的时刻距现在的时间,单位是毫秒,指定为“0”表示立即启动计时器;
// 第四个参数:定时器的时间间隔——计时开始以后,每隔这么长的一段时间,timercallback所代表的方法将被调用一次,单位也是毫秒。指定 timeout.infinite 可以禁用定期终止。
timer.change()方法:修改定时器的设置。(这是一个参数类型重载的方法)
使用示例: timer.change(1000,2000);
timer类的程序示例(来源:msdn):
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;
}
程序首先创建了一个定时器,它将在创建1秒之后开始每隔1秒调用一次checkstatus()方法,当调用5次以后,在checkstatus()方法中修改了时间间隔为2秒,并且指定在10秒后重新开始。当计数达到10次,调用timer.dispose()方法删除了timer对象,主线程于是跳出循环,终止程序。