zoukankan      html  css  js  c++  java
  • C# timer类的用法

    C#中timer类的用法

    关于C#中timer类  在C#里关于定时器类就有3个   
    1.定义在System.Windows.Forms里   
    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,完全取代上面的Timer控件。它们的缺点是不支持直接的拖放,需要手工编码。

    例: 
    使用System.Timers.Timer类 
    //实例化Timer类,设置间隔时间为10000毫秒; 
    System.Timers.Timer t = new System.Timers.Timer(10000);
    //到达时间的时候执行事件;
    t.Elapsed += new System.Timers.ElapsedEventHandler(theout); 
    t.AutoReset = true;//设置是执行一次(false)还是一直执行(true); 
    t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;

    ====================================

    "只要在使用 Timer,就必须保留对它的引用。
    "对于任何托管对象,如果没有对 Timer 的引用,计时器会被垃圾回收。即使 Timer 仍处在活动状态,也会被回收。
    "当不再需要计时器时,请使用 Dispose 方法释放计时器持有的资源。

    ====================================

    应用场景:在windows form程序定时自动执行某项工作。

    我写的参考代码:

        //我的计时器-用System.Threading.Timer   
        //效果:第一次等3秒弹出提示框,以后每5秒弹出提示框
        //用法:在form1中声明 public Mytimer mytimer = new Mytimer();这样只要form1不退出mytimer就不会被GC回收。
        public class Mytimer
        {
            private System.Threading.Timer timer1;
            //构造函数
            public Mytimer()
            {
                // Create a timer thread and start it
                this.timer1 = new System.Threading.Timer(new TimerCallback(timer1Call), this, 3000, 5000);
                //Timer构造函数参数说明:
                //Callback:一个 TimerCallback 委托,表示要执行的方法。
                //State:一个包含回调方法要使用的信息的对象,或者为空引用(Visual Basic 中为 Nothing)。
                //dueTime:调用 callback 之前延迟的时间量(以毫秒为单位)。指定 Timeout.Infinite 以防止计时器开始计时。指定零(0) 以立即启动计时器。
                //Period:调用 callback 的时间间隔(以毫秒为单位)。指定 Timeout.Infinite 可以禁用定期终止。
            }
    
            private void timer1Call(object state)
            {
                MessageBox.Show("timer1:" + state.ToString());            
            }
        }

    参考:https://www.cnblogs.com/youmingkuang/p/9987672.html

    https://www.cnblogs.com/yank/archive/2007/12/03/981238.html

    https://blog.csdn.net/imxiangzi/article/details/80551193

  • 相关阅读:
    年末反思
    Flink运行时架构
    Phoenix 启动报错:Error: ERROR 726 (43M10): Inconsistent namespace mapping properties. Cannot initiate connection as SYSTEM:CATALOG is found but client does not have phoenix.schema.
    Clickhouse学习
    Flink简单认识
    IDEA无法pull代码到本地,Can't Update No tracked branch configured for branch master or the branch doesn't exist.
    第1章 计算机系统漫游
    简单的 Shell 脚本入门教程
    开源≠免费 常见开源协议介绍
    MySQL 视图
  • 原文地址:https://www.cnblogs.com/pu369/p/12372189.html
Copyright © 2011-2022 走看看