zoukankan
html css js c++ java
线程中Timer类使用(摘自cnblogs)
下面这段程序演示了Timer类的用法。
using
System;
using
System.Threading;
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(
5000
,
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秒,并且指定在5秒后重新开始。当计数达到10次,调用Timer.Dispose()方法删除了timer对象,主线程于是跳出循环,终止程序。
查看全文
相关阅读:
LeetCode OJ-- 二战 Palindrome Number
Cracking-- 17.13 将二叉树转换成双向链表
Cracking-- 4.7 在一颗二叉树中找两个节点的第一个共同祖先
priority_queue 示例
heap c++ 操作 大顶堆、小顶堆
【转】当你在浏览器地址栏输入一个URL后回车,将会发生的事情?
Cracking-- 1.1 判断字符串中是否有重复字符
如何取得SharePoint Timer Job的历史成功数和失败数,并按照日期计算排列
SharePoint document 右键菜单和【...】菜单不一致的解决办法
SharePoint Search 分词(WordBreaker)
原文地址:https://www.cnblogs.com/xiaobaigang/p/930238.html
最新文章
[S5PV210] 网络挂载文件系统
Ubuntu gedit 添加编码格式
[转] 栈的作用
RAM & ROM
[Freescale] LCD 噪点修正
[Android] 关于Window Overscan
[Freescale] libzlo2 & libuuid install
[Freescale] LCD Driver Porting
Phos 技术服务支持
Theos
热门文章
Dumpsdecrypted
Class-dump
CentOS 安装 MySQL
CentOS7 安装 Tomcat
03 Java 修饰符
02 Java 基础语法
01 Java 搭建环境
LeetCode OJ-- Single Number II **@
python subprocess 自动运行实验室程序
LeetCode OJ-- 二战 Combinations
Copyright © 2011-2022 走看看