C# 中有四种定时器

目录

C# / .Net中的四种定时器:

1、System.Threading.Timer

2:System.Timers.Timer

3:System.Windows.Forms.Timer(Windows Forms Timer)

4:System.Windows.Threading.DispatcherTimer(WPF timer);


C# / .Net中的四种定时器:

        System.Windows.Forms.Timer类型(Winfrom专用)

        System.Threading.Timer类型

        System.Timers.Timer类型

        System.Windows.Threading.DispatcherTimer类型(WPF专用)

**************************************************************************************************************

1、System.Threading.Timer

private System.Threading.Timer timerClose;
timerClose = new System.Threading.Timer(new TimerCallback(timerCall), this, 5000, 0);

private void timerCall(object obj)
{
     timerClose.Dispose();
     this.Close();
}

2:System.Timers.Timer

System.Timers.Timer t =  new System.Timers.Timer(10000);
//实例化Timer类,设置间隔时间为10000毫秒;
t.Elapsed +=  new System.Timers.ElapsedEventHandler(theout);
//到达时间的时候执行事件;
t.AutoReset = true;
//设置是执行一次(false)还是一直执行(true);
t.Enabled = true;
//需要调用 timer.Start()或者timer.Enabled = true来启动它, timer.Start()的内部原理还是设置timer.Enabled = true;

public void theout(object source, System.Timers.ElapsedEventArgs e)
{

}

3:System.Windows.Forms.Timer(Windows Forms Timer)

System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();

myTimer.Tick += new EventHandler(timer1_Tick);
myTimer.Enabled = true;
myTimer.Interval = 1000;
myTimer.Start();

private void timer1_Tick(object sender, EventArgs e)
{
}

4:System.Windows.Threading.DispatcherTimer(WPF timer);

public DispatcherTimer SysInTimer = new System.Windows.Threading.DispatcherTimer();
SysInTimer.Tick += new EventHandler(Srcinf);
SysInTimer.Interval = TimeSpan.FromSeconds(15);
SysInTimer.Start();

 public void Srcinf(object sender, EventArgs e)
{

}

        注意的是在wpf中涉及到界面操作的话,一定要使用第四种定时器DispatcherTime,DispatcherTimer是为wpf专门设计的,不然的话会提示界面资源被其他线程所拥有而无法更新界面。

**************************************************************************************************************

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值