C# 计时器的三种使用方法

摘要:
Timer控件及其形式属于同一线程;系统计时器。计时器类:定义系统。Timers Timer对象,绑定Elapsed事件,通过start()方法开始计时,通过stop()方法或Enable=False停止计时。TimerCallBack是一个委托,其返回值为void,参数为object,也是计时器执行的方法。指定超时无限以防止计时器开始计时。指定零以立即启动计时器。第二个和第三个计时器执行方法都启动一个新的线程,因此执行效率比第一个计时器好。因此,在使用计时器时,建议使用第二种和第三种类型。

在.net中有三种计时器,一是System.Windows.Forms命名空间下的Timer控件,它直接继承自Componet;二是System.Timers命名空间下的Timer类。

Timer控件:Timer控件只有绑定了Tick事件,和设置Enabled=True后才会自动计时,停止计时可以用Stop()控制,通过Stop()停止之后,如果想重新计时,可以用Start()方法来启动计时器。Timer控件和它所在的Form属于同一个线程;

System.Timers.Timer类:定义一个System.Timers.Timer对象,绑定Elapsed事件,通过Start()方法启动计时,通过Stop()方法或者Enable=False停止计时。AutoReset属性设置是否重复计时。Elapsed事件绑定就相当另开了一个线程,也就是说在Elapsed绑定的事件里不能访问其它线程里的控件。

System.Threading.Timer:定义该类时,主要有四个参数。TimerCallBack,一个返回值为void,参数为object的委托,也是计时器执行的方法。Object state,计时器执行方法的的参数。 int dueTime,调用 callback 之前延迟的时间量(以毫秒为单位)。指定 Timeout.Infinite 以防止计时器开始计时。指定零 (0) 以立即启动计时器。

int Period,调用 callback 的时间间隔(以毫秒为单位)。指定 Timeout.Infinite 可以禁用定期终止。

在这三种计时器中,第一种计时器和所在的Form处于同一个线程,因此执行的效率不高。而第二种和第三中计时器执行的方法都是新开一个线程,所以执行效率比第一种计时器要好。因此在使用计时器时,建议使用第二种和第三种。

下面是三中定时器使用的例子

1)Timer控件  

  public partial class Timer : Form
    {

        int count = 0;
        public Timer()
        {
            InitializeComponent();

            //timer控件可用
            this.timer1.Enabled = true;

           //设置timer控件的Tick事件触发的时间间隔
            this.timer1.Interval = 1000;

            //停止计时
            this.timer1.Stop();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            count += 1;
            this.tbTimer.Text = count.ToString();
        }

        private void btStart_Click(object sender, EventArgs e)
        {
            //开始计时
            this.timer1.Start();
        }

        private void btStop_Click(object sender, EventArgs e)
        {
            //停止计时
            this.timer1.Stop();
            
        }

    }

2)System.Timers.Timer

public partial class Timer : Form
    {
        int count = 0;

        private System.Timers.Timer timer = new System.Timers.Timer();

        public Timer()
        {
            InitializeComponent();

            //设置timer可用
            timer.Enabled = true;
            
            //设置timer
            timer.Interval = 1000;

            //设置是否重复计时,如果该属性设为False,则只执行timer_Elapsed方法一次。
            timer.AutoReset = true;

            timer.Elapsed+=new System.Timers.ElapsedEventHandler(timer_Elapsed);
        }

        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
        {
            count += 1;
            SetTB(count.ToString());
        }

        private void btStart_Click(object sender, EventArgs e)
        {
            timer.Start();
        }

        private void btStop_Click(object sender, EventArgs e)
        {
            timer.Stop();
        }

        private delegate void SetTBMethodInvok(string value);

        private void SetTB(string value)
        {
            if (this.InvokeRequired) 
            {
                this.Invoke(new SetTBMethodInvok(SetTB), value);
            }
            else
            {
                this.tbTimer.Text = value;
            }
        }
    }

3) System.Threading.Timer

    public partial class Timer : Form
    {
        int count = 0;
        System.Threading.Timer timerThr;
        private delegate void SetTBMethodInvoke(object state);

        public Timer()
        {
            InitializeComponent();

            //初始化一个计时器,一开始不计时,调用Callback的时间间隔是500毫秒
            timerThr = new System.Threading.Timer(new TimerCallback(SetTB), null, Timeout.Infinite, 500);
        }

        public void SetTB(object value)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new SetTBMethodInvoke(SetTB), value);
            }
            else 
            {
                count += 1;
                this.tbTimer.Text = count.ToString();
            }
        }

        private void btStart_Click(object sender, EventArgs e)
        {
            //开始计时
            timerThr.Change(0, 500);
        }

        private void btStop_Click(object sender, EventArgs e)
        {
            //停止计时
            timerThr.Change(Timeout.Infinite, 500);
        }
    }

免责声明:文章转载自《C# 计时器的三种使用方法》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇编译 FFmpeg h263 decoder出现编译错误undefined reference to `ff_find_pix_fmt'PL/SQL 导入excel表格到oracle数据表下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Scala中class、object、case class、case object区别

/** class、object、case class、case object区别 * * class 类似Java中的class; * object Scala不能定义静态成员,用定义单例对象代之; * case class被称为样例类,是一种特殊的类,常被用于模式匹配。 * * 一、class 和 object 关系: *...

JS输出为[object Object] 如何解决

[object Object] 直接转成json 二行js代码搞定 var str = Java.use('java.lang.String') console.log(' str ', str.$new(args1)) Des3Encrypt.sign.overload('[B','java.lang.String').implementation =...

Mybatis拦截器实现SQL性能监控

Mybatis拦截器只能拦截四类对象,分别为:Executor、ParameterHandler、StatementHandler、ResultSetHandler,而SQL数据库的操作都是从Executor开始,因此要记录Mybatis数据库操作的耗时,需要拦截Executor类,代码实现如下: /*** 数据库操作性能拦截器,记录耗时 * @Inte...

海量小文件存储与Ceph实践

  海量小文件存储(简称LOSF,lots of small files)出现后,就一直是业界的难题,众多博文(如[1])对此问题进行了阐述与分析,许多互联网公司也针对自己的具体场景研发了自己的存储方案(如taobao开源的TFS,facebook自主研发的Haystack),还有一些公司在现有开源项目(如hbase,fastdfs,mfs等)基础上做针对...

前台和后台的相互传值

目录 一、把json对象转成字符串 二、创建数据容器对象 [用来绑定要传给后台的前台控件值] 三、创建绑定前台数据对象 [用来读取后台传过来的值,并绑定到前台页面] 四、使用示例 前后台的相互传值如果值太多,写的麻烦累人,且容易出错。这里整理出一套使用标记 标签属性的办法来传值, 后台取值和前台的绑定都有了大大的简化。 一、把json对象转成字符串 1...

学习笔记之C# 教程 | 菜鸟教程

C# 教程 | 菜鸟教程 http://www.runoob.com/csharp/csharp-tutorial.html 菜鸟教程在线编辑器 http://www.runoob.com/try/runcode.php?filename=HelloWorld&type=cs C# Programming Guide - 介绍了有关关键的 C#...