会员
周边
众包
新闻
博问
闪存
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
笑萧亦然
做一个有用的程序员 每天都有前进的方向,每天都有新的起点。当我白发时才会有回忆的往事。
博客园
首页
新随笔
联系
订阅
管理
VSTS2008 学习之路(2):多线程Timer
今天学习一下多线程在网络上看到一个很好的例子,简单而且很好理解。
Code
1
namespace
ThreadTest
2
{
3
using
System;
4
using
System.Threading;
5
class
TimerExampleState
6
{
7
public
int
counter
=
0
;
8
public
Timer tmr;
9
}
10
class
App
11
{
12
public
static
void
Main()
13
{
14
TimerExampleState s
=
new
TimerExampleState();
15
16
//
创建代理对象TimerCallback,该代理将被定时调用
17
TimerCallback timerDelegate
=
new
TimerCallback(CheckStatus);
18
19
//
创建一个时间间隔为1s的定时器
20
Timer timer
=
new
Timer(timerDelegate, s,
1000
,
1000
);
//
在超过 dueTime 后及此后每隔 period 时间间隔,都会调用一次由 callback 参数指定的委托。
21
s.tmr
=
timer;
22
23
//
主线程停下来等待Timer对象的终止
24
while
(s.tmr
!=
null
)
25
{
26
Thread.Sleep(
0
);
27
}
28
Console.WriteLine(
"
Timer example done.
"
);
29
Console.ReadLine();
30
}
31
//
file:
//
下面是被定时调用的方法
32
33
static
void
CheckStatus(Object state)
34
{
35
TimerExampleState s
=
(TimerExampleState)state;
36
s.counter
++
;
37
Console.WriteLine(
"
{0} Checking Status {1}.
"
, DateTime.Now.TimeOfDay, s.counter);
38
if
(s.counter
==
5
)
39
{
40
file:
//
使用Change方法改变了时间间隔
41
(s.tmr).Change(
10000
,
2000
);
42
Console.WriteLine(
"
changed
"
);
43
}
44
if
(s.counter
==
10
)
45
{
46
Console.WriteLine(
"
disposing of timer
"
);
47
s.tmr.Dispose();
48
s.tmr
=
null
;
49
}
50
}
51
}
52
}
53
posted @
2009-05-09 15:30
笑萧亦然
阅读(
235
) 评论(
0
)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面
返回顶部
公告