使用计时器
简介
在线程池中建立周期性的异步操作。
以下是代码实践:
using System;
using System.Threading;
namespace 使用计时器
{
internal class Program
{
private static void Main()
{
Console.WriteLine("Press 'Enter' to stop the timer...");
var start = DateTime.Now;
//初始化定时器实例,设置回调函数,第一次调用时间和以后每次调用的时间间隔。
_timer = new Timer(_ => TimerOperation(start), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));
Thread.Sleep(TimeSpan.FromSeconds(6));
_timer.Change(TimeSpan.FromSeconds(1),TimeSpan.FromSeconds(4));
Console.ReadLine();
_timer.Dispose();
}
private static Timer _timer;
private static void TimerOperation(DateTime start)
{
var elapsed = DateTime.Now - start;
Console.WriteLine("{0} second from {1}. Timer thread pool thread id: {2}", elapsed.Seconds, start,
Thread.CurrentThread.ManagedThreadId);
}
}
}
总结
可以通过Timeout.Infinet值提供给计时器一个间隔参数来只允许计时器操作一次。然后在异步操作内设置下一次操作被执行的时间。具体时间取决于自定义的业务逻辑。这篇比较简单,不做过多的描述。
备注:学习《Multithreading in C# 5.0 Cookbook》Eugene Agafonov著的总结,以备日后查询。