C#实现定时器的几种方案

在C#里关于定时器类就有三个

1、System.Windows.Forms.Timer

2、System.Threading.Timer

3、定义在System.Timers.Timer

下面对这三个类进行讲解。

System.Windows.Forms.Timer是应用于WinForm中的,它是通过Windows消息机制实现的,类似于VB或Delphi中  的Timer控件,内部使用API SetTimer实现的。它的主要缺点是计时不精确,而且必须有消息循环,Console  Application(控制台应用程序)无法使用。

System.Timers.Timer和System.Threading.Timer非常类似,它们都是通过.NET  Thread  Pool实现的,轻量,计时精确,对应用程序、消息没有特别的要求。System.Timers.Timer还可以应用于WinForm,完全取代上面的System.Windows.Forms.Timer控件。

System.Windows.Forms.Timer

计时器最宜用于 Windows 窗体应用程序中,并且必须在窗口中使用,适用于单线程环境,

在此环境中, UI 线程用于执行处理。它要求用户代码提供 UI 消息泵, 并且始终从同一线程操作, 或将调用封送到

其他线程。Windows 窗体计时器组件是单线程的, 且限制为55毫秒的准确度,准确性不高

public partial class frmTimerDemo : Form
 {
 private System.Windows.Forms.Timer timerGetTime;

 private void frmTimerDemo_Load(object sender, EventArgs e)
 {
 //创建定时器
 timerGetTime = new System.Windows.Forms.Timer();
 //设置定时器属性
 timerGetTime.Tick+=new EventHandler(HandleTime);
 timerGetTime.Interval = 1000;
 timerGetTime.Enabled = true;
 //开启定时器
 timerGetTime.Start();
 }
 public void HandleTime(Object myObject, EventArgs myEventArgs)
 {
 labelTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
 }
 private void frmTimerDemo_FormClosed(object sender, FormClosedEventArgs e)
 {
 //停止定时器
 timerGetTime.Stop();
 }
 }

System.Timers.Timer

这个是目前我们定时项目中常用的。

System.Timers.Timer t = new System.Timers.Timer(10000);//实例化Timer类,设置间隔时间为10000毫秒;
t.Elapsed += new System.Timers.ElapsedEventHandler(Execute);//到达时间的时候执行事件;
t.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
t.Start(); //启动定时器
//上面初始化代码可以写到构造函数中

 
public void Execute(object source, System.Timers.ElapsedEventArgs e)
{
 t.Stop(); //先关闭定时器
 MessageBox.Show("OK!");
t.Start(); //执行完毕后再开启器
}

这里需要注意的是Execute方法中一定要先关闭定时器,执行完毕后再开启。这个是本人经过测试的,如果你注释掉这两句,定时器会不断的执行Execute方法,如果Execute执行的是一个很耗时的方法,会导致方法未执行完毕,定时器又启动了一个线程来执行Execute方法。

System.Threading.Timer

线程计时器也不依赖窗体,是一种简单的、轻量级计时器,它使用回调方法而不是使用事件,并由线程池线程提供支持,先看下面代码

class Program
 {
 int TimesCalled = 0;
 void Display(object state)
 {
 Console.WriteLine("{0} {1} keep running.", (string)state, ++TimesCalled);
 }
 static void Main(string[] args)
 {
 Program p = new Program();
 //2秒后第一次调用,每1秒调用一次
 System.Threading.Timer myTimer = new System.Threading.Timer(p.Display, "Processing timer event", 2000, 1000);
 // 第一个参数是:回调方法,表示要定时执行的方法,第二个参数是:回调方法要使用的信息的对象,或者为空引用,第三个参数是:调用 callback 之前延迟的时间量(以毫秒为单位),指定 Timeout.Infinite 以防止计时器开始计时。指定零 (0) 以立即启动计时器。第四个参数是:定时的时间时隔,以毫秒为单位

 Console.WriteLine("Timer started.");
 Console.ReadLine();
 }
}

上面是c#定时器的集中方案,大家在使用中一定要尽量把定时器声明成静态(static),如果放在实例方法中,会导致实例对象被回收导致定时器失效。

-----------------------------------

公众号【Csharp编程大全】,需要进技术群交流的,请添加小编mm1552923!

C# 中,你可以使用以下几种方法来实现定时器功能: 1. System.Timers.Timer:这是一个基于线程的定时器,可以在指定的时间间隔内重复执行指定的代码。你可以设置 Interval 属性来指定时间间隔,并通过 Elapsed 事件来处理计时器事件。 ```csharp using System; using System.Timers; public class TimerExample { private static Timer timer; public static void Main() { timer = new Timer(); timer.Interval = 1000; // 设置时间间隔为1秒 timer.Elapsed += TimerElapsed; // 绑定事件处理程序 timer.Enabled = true; // 启动计时器 Console.WriteLine("Press Enter to stop the timer."); Console.ReadLine(); timer.Enabled = false; // 停止计时器 } private static void TimerElapsed(object sender, ElapsedEventArgs e) { Console.WriteLine("Timer elapsed at {0}", e.SignalTime); } } ``` 2. System.Threading.Timer:这是一个基于线程池的定时器,也可以在指定的时间间隔内重复执行指定的代码。你可以使用 Change 方法来设置时间间隔,并通过 TimerCallback 委托来处理计时器事件。 ```csharp using System; using System.Threading; public class TimerExample { private static Timer timer; public static void Main() { TimerCallback callback = new TimerCallback(TimerElapsed); timer = new Timer(callback, null, 0, 1000); // 设置时间间隔为1秒 Console.WriteLine("Press Enter to stop the timer."); Console.ReadLine(); timer.Dispose(); // 停止计时器 } private static void TimerElapsed(object state) { Console.WriteLine("Timer elapsed at {0}", DateTime.Now); } } ``` 3. System.Threading.Tasks.Task.Delay:这是一种基于异步任务的延迟执行方法,可以在指定的时间间隔后执行指定的代码。 ```csharp using System; using System.Threading.Tasks; public class TimerExample { public static async Task Main() { Console.WriteLine("Press Enter to start the timer."); Console.ReadLine(); while (true) { Console.WriteLine("Timer elapsed at {0}", DateTime.Now); await Task.Delay(1000); // 设置时间间隔为1秒 } } } ``` 这些是在 C#实现定时器功能的几种常用方法。你可以根据自己的需求选择适合的方法来实现定时器功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值