• C#中的System.Windows.Forms.Timer,System.Tiemrs.Timer,System.Thread.Timer,System.Web.UI.Timer


    在C#中有4类Timer,分别如下:

    1.System.Windows.Forms.Timer,顾名思义该Timer是Winform中的一个控件,可以拖放到窗体之上,设置它的Interval属性和Tick事件即可,同时要设置Enable为true(启用,另外该Timer属于UI级别的,即执行该Timer会造成UI阻塞。

    2.System.Timers.Timer,该线程是通过Thread Pool来完成的,和UI不是一个线程的,所以不用担心阻塞的情况,该Timer和System.Thread.Timer非常类似都是通过Thread Pool,但是该Timer的初次触发事件是在设定的Interval之后的,即首次运行也需要等待一个时间才会执行,而System.Thread.Timer是首次会执行,从第二次开始才是间隔时间.

    3.System.Thread.Timer,该线程是通过Thread Pool来完成的,和UI不是一个线程的,所以不用担心阻塞的情况。该Timer是通过回调绑定的方式实现即时的,当然在声明和使用上与System.Timers.Timer还是有很大的差别,同时还可以指定执行的等待时间,即在某次回调开始前等待多久(是在Interval计算之后)。

    看个实例:

    这个是System.Timers.Timer的例子:

                System.Timers.Timer timerPing = new System.Timers.Timer(900000);//指定间隔事件,以毫秒计算
    timerPing.Elapsed += new System.Timers.ElapsedEventHandler(timerPing_Elapsed);//绑定调用的事件
    timerPing.AutoReset = true;//设置为自动调用
    timerPing.Enabled = true;//启用
    timerPing.Start();//调用开始方法
     void timerPing_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
    //dosomething
    }


    以下是System.Threading.Timer的例子:

    可以看到它的定义和System.Timers.Timer有很大的差别,第一个参数为回调函数,该函数需要是一个参数为object类型的参数,第二个参数为回调函数的参数值,可以为

    空,第三个参数为调用回调函数的延迟时间,第四个参数为回调函数的间隔事件(经实例验证,当不传递延迟时间参数会出现timer停止的情况,具体原因不明确).

    System.Threading.Timer timerPing= new System.Threading.Timer(StatisticaData, null, 1000, 3600000);

      void StatisticaData(object state)
    {
    //dosomething;
    }


    以上就是简单的几个Timer的介绍,望多多指正。


  • 相关阅读:
    算法总结--排序(快排未写)
    关于我,至目前的总结与展望
    二 python之数据类型和字符编码
    三 python之文件处理
    一 python编程基础
    markdown语法
    规模-复杂世界的简单法则---熵
    块级元素display:inline-block 在IE6 IE7无效
    CSS3 文本超出后显示省略号...
    让nodejs在iis上运行
  • 原文地址:https://www.cnblogs.com/ListenFly/p/2218672.html
Copyright © 2020-2023  润新知