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对象,主线程于是跳出循环,终止程序。
查看全文
相关阅读:
085 Maximal Rectangle 最大矩形
084 Largest Rectangle in Histogram 柱状图中最大的矩形
083 Remove Duplicates from Sorted List 有序链表中删除重复的结点
082 Remove Duplicates from Sorted List II 有序的链表删除重复的结点 II
081 Search in Rotated Sorted Array II 搜索旋转排序数组 ||
080 Remove Duplicates from Sorted Array II 从排序阵列中删除重复 II
079 Word Search 单词搜索
078 Subsets 子集
bzoj2326: [HNOI2011]数学作业
bzoj2152: 聪聪可可
原文地址:https://www.cnblogs.com/xiaobaigang/p/930238.html
最新文章
node 大牛的blog
get与post
webstorm11的激活
angular(常识)
s6 传输层
s6 传输层
s3-1 数据链路层概述
s3-1 数据链路层概述
linux常用快捷键
hihoCoder 挑战赛10 #1144 : 01串
热门文章
hihoCoder #1038 : 01背包
编程之美2015 资格赛 hihocoder 题目2: 回文字符序列
常用函数
HDU 1305 Immediate Decodability 可直接解码吗?
LeetCode Implement strStr() 实现strstr()
hihoCoder #1143 : 骨牌覆盖问题·一 (斐波那契数列)
LeetCode Excel Sheet Column Number 表列数
LeetCode Rotate Array 翻转数组
087 Scramble String 扰乱字符串
086 Partition List 分隔链表
Copyright © 2011-2022 走看看