C#多线程学习(五) 多线程的自动管理(定时器) (转载)
Timer类:设置一个定时器,定时执行用户指定的函数。
定时器启动后,系统将自动建立一个新的线程,执行用户指定的函数。初始化一个Timer对象:
Timer timer = new Timer(timerDelegate, s,1000, 1000);
// 第二个参数:一个包含回调方法要使用的信息的对象,或者为空引用;
// 第三个参数:延迟时间——计时开始的时刻距现在的时间,单位是毫秒,指定为“0”表示立即启动计时器;
// 第四个参数:定时器的时间间隔——计时开始以后,每隔这么长的一段时间,TimerCallback所代表的方法将被调用一次,单位也是毫秒。指定 Timeout.Infinite 可以禁用定期终止。
Timer.Change()方法:修改定时器的设置。(这是一个参数类型重载的方法)
使用示例: timer.Change(1000,2000);
Timer类的程序示例(来源:MSDN):
using System;
using System.Threading;
namespace ThreadExample
{
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(10000,2000);
Console.WriteLine("changed
");
}
if(s.counter == 10)
{
Console.WriteLine("disposing of timer
");
s.tmr.Dispose();
s.tmr = null;
}
}
}
}
using System.Threading;
namespace ThreadExample
{
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(10000,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秒,并且指定在10秒后重新开始。当计数达到10次,调用Timer.Dispose()方法删除了timer对象,主线程于是跳出循环,终止程序。
分类:
C#基础学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗