码迷,mamicode.com
首页 > Windows程序 > 详细

C#定时器

时间:2019-03-12 15:34:38      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:启动   winform   pre   ini   应用程序   res   win   时间   rgs   

简介

在C#中可以有三种方式实现定时器,分别在以下三个类中。

1.定义在System.Windows.Forms里

2.定义在System.Threading.Timer类里

3.定义在System.Timers.Timer类里

第一种:System.Windows.Forms类

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

第二种 System.Timers.Timer类:

#region 
public void StartRecvDataTimer( Boolean autoFlag )
{
    //实例化Timer类,设置间隔时间为10000毫秒;
    System.Timers.Timer t = new System.Timers.Timer(3000);
    t.Elapsed += new System.Timers.ElapsedEventHandler(ShowRecv);
    t.AutoReset = autoFlag;//设置是执行一次(false)还是一直执行(true);
    t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
}

//到达时间的时候执行事件;
public void ShowRecv(object source, System.Timers.ElapsedEventArgs e)
{
    MessageBox.Show("nihao");
}
#endregion

第三种:System.Threading.Timer类

该类使用回调方法的计时器,而且由线程池线程服务,简单且对资源要求不高。

使用 TimerCallback 委托指定希望 Timer 执行的方法。计时器委托在构造计时器时指定,并且不能更改。此方法不在创建计时器的线程中执行,而是在系统提供的线程池线程中执行。

创建计时器时,可以指定在第一次执行方法之前等待的时间量(截止时间)以及此后的执行期间等待的时间量(时间周期)。可以使用 Change 方法更改这些值或禁用计时器。

应用场景:在windows form程序自动执行某项工作后,希望其windows form能够自动关闭。

    public void StartRecvDataTimer1( )
    {
        timerClose = new System.Threading.Timer(new TimerCallback(timerCall), this, 1000,0);
    }

    //委托执行的方法
    private void timerCall(object obj)
    {
        MessageBox.Show("nihao");
    }

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

C#定时器

标签:启动   winform   pre   ini   应用程序   res   win   时间   rgs   

原文地址:https://www.cnblogs.com/qq-375291943/p/10516889.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!