您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

C# 定时器Timer的实例介绍

2024/2/26 13:27:48发布23次查看
static void main(string[] args) { #region 定时器 timerdemo td = new timerdemo("timerdemo", 1000); td.enabled = true; td.tickevent += testhandler; thread timer = new thread(td.run); timer.start(); #endregion console.readline(); } /// <summary> /// 测试用事件 /// </summary> static void testhandler() { console.writeline(datetime.now.tolongtimestring()); }
public class timerdemo { //线程名 string _threadname; public string threadname { get { return _threadname; } private set { _threadname = value; } } //时间间隔 int _timeinterval; public int timeinterval { get { return _timeinterval; } set { _timeinterval = value; } } //当前计时器是否启用 true:启用 false:不启用 bool _enabled; public bool enabled { get { return _enabled; } set { _enabled = value; } } //每隔一段时间需要运行的事件 public delegate void tickeventhandler(); public event tickeventhandler tickevent; /// <summary> /// 建立一个计时器(构造函数) /// </summary> /// <param name="threadname">线程名</param> /// <param name="timeinterval">时间间隔</param> public timerdemo(string threadname, int timeinterval = int.maxvalue) { this.threadname = threadname; this.timeinterval = timeinterval; this.enabled = false; } /// <summary> /// 定期执行事件 /// </summary> public void run() { while (true) { //如果当前计时器并未启用,则每隔一段时间检测是否被启用 if (!this.enabled) { thread.sleep(100); continue; } //触发事件tickevent if (tickevent != null) { tickevent(); } //休眠一定的时间,等待下一个循环 thread.sleep(timeinterval % 100); for (int temp = 0; temp < timeinterval / 100; temp++) { thread.sleep(100); if (!this.enabled) { break; } } } } }
以上就是c# 定时器timer的实例介绍的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product