System.Threading.Timer用法

(1)首先声明Timer变量:
//一定要声明成局部变量以保持对Timer的引用,否则会被垃圾收集器回收!
private System.Threading.Timer timerClose;

(2)在上述自动执行代码后面添加如下Timer实例化代码:
// Create a timer thread and start it
timerClose = new System.Threading.Timer(new TimerCallback(timerCall), this, 5000, 0);

//Timer构造函数参数说明:
Callback:一个 TimerCallback 委托,表示要执行的方法。
State:一个包含回调方法要使用的信息的对象,或者为空引用(Visual Basic 中为 Nothing)。
dueTime:调用 callback 之前延迟的时间量(以毫秒为单位)。指定 Timeout.Infinite 以防止计时器开始计时。指定零 (0) 以立即启动计时器。
Period:调用 callback 的时间间隔(以毫秒为单位)。指定 Timeout.Infinite 可以禁用定期终止。

(3)定义TimerCallback委托要执行的方法:
private void timerCall(object obj)
{
timerClose.Dispose();
this.Close();
}

当然,除了使用上述System.Threading.Timer类的TimerCallback 委托机制外,应该还有很多其他的办法。
另外,这里只是demo了TimerCallback委托的简单应用。

实例如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace MYTimerTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(timer_Elapsed), null, 0, 1000);
}

void timer_Elapsed(object sender)
{
for (int i = 0; i < 10; i++)
{
Console.Out.WriteLine(DateTime.Now + " " + DateTime.Now.Millisecond.ToString() + “timer in:”);
}

}
}
}

注意void timer_Elapsed(object sender)中的“object”对应new System.Threading.Timer(new TimerCallback(timer_Elapsed), null, 0, 1000)中的

第二个参数。

猜你喜欢

转载自blog.csdn.net/qq_30725967/article/details/88890379
今日推荐