C#多线程学习(五) 多线程的自动管理(定时器)
Timer类:设置一个定时器,定时执行用户指定的函数。
定时器启动后,系统将自动建立一个新的线程,执行用户指定的函数。
Timer timer = new Timer(timerDelegate, s,1000, 1000);
// 第一个参数:指定了TimerCallback 委托,表示要执行的方法;
// 第二个参数:一个包含回调方法要使用的信息的对象,或者为空引用;
// 第三个参数:延迟时间——计时开始的时刻距现在的时间,单位是毫秒,指定为“0”表示立即启动计时器;
// 第四个参数:定时器的时间间隔——计时开始以后,每隔这么长的一段时间,TimerCallback所代表的方法将被调用一次,单位也是毫秒。指定 Timeout.Infinite 可以禁用定期终止。
Timer.Change()方法:修改定时器的设置。(这是一个参数类型重载的方法)
使用示例:
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;
}
}
}
}
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;
}
}
}
}
最后更新:2017-04-02 00:06:39
上一篇:
C++流实现内幕---由boost::lexical_cast引发的一个问题
下一篇:
开始了IBM的新生活
ubuntu12.04 64位系统配置jdk1.6和jdk-6u20-linux-i586.bin下载地址
js 数据类型及常用函数
MongoDB查询优化:从 10s 到 10ms
3d图形渲染中表层GUI制作的一种方法
java 企业网站源码 后台 springmvc SSM 前台freemaker 静态化 代码生成器
Android App监听软键盘按键的三种方式
巧用CSS3滤镜实现图片不同渲染效果
阿里云ECS如何部署并运行一个JavaWeb项目
《Redis官方文档》Data types—数据类型
9月28日云栖精选夜读:阿里云MaxCompute澳大利亚开服,“领跑”人工智能市场