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对象,主线程于是跳出循环,终止程序。
查看全文
相关阅读:
ansible 使用密码登录
shell脚本报错:-bash: xxx: /bin/bash^M: bad interpreter: No such file or directory
配置永久生效(登陆shell和非登陆shell)、I/O重定向、Here Docunmet 此处文档、管道、tee
Navicat for PostgreSQL 序列详解
flask第十五篇——Response
Centos防火墙及SELINUX关闭
linux查看网卡信息的几种方法(命令)
Python之在函数中调用import语句
python基础_格式化输出(%用法和format用法)
Python中怎样简单地用一行写if-then语句?
原文地址:https://www.cnblogs.com/xiaobaigang/p/930238.html
最新文章
油猴安装、编写及添加脚本 笔记
【教程、无技术含量】简单的油猴脚本编写教程
PostgreSQL简单介绍
Juery Ajax语法
VS2013 当前不会命中断点,还没有为该文档加载任何符号
程序员必须知道的几个Git代码托管平台
写给自己
代码重构——程序员应有的基因
态度以及业余付出决定程序生涯
常用正则表达式
热门文章
Web API应用架构设计分析(2)
基于Centos搭建nginx+uwsgi运行django环境
percona-xtrabackup备份mysql
python3.6环境部署文档
django开发环境部署之pip、virtualenv、virtualenvwrapper
python利用WMI监控windows状态如CPU、内存、硬盘
python之生成excel
python之psutil模块(获取系统性能信息(CPU,内存,磁盘,网络)
查看Linux服务器CPU使用率、内存使用率、磁盘空间占用率、负载情况
python调用top命令获得CPU利用率
Copyright © 2011-2022 走看看