在.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# 计时器的三种使用方法的更多相关文章

  1. javase-常用三种遍历方法

    javase-常用三种遍历方法 import java.util.ArrayList; import java.util.Iterator; import java.util.List; public ...

  2. JS面向对象(3) -- Object类,静态属性,闭包,私有属性, call和apply的使用,继承的三种实现方法

    相关链接: JS面向对象(1) -- 简介,入门,系统常用类,自定义类,constructor,typeof,instanceof,对象在内存中的表现形式 JS面向对象(2) -- this的使用,对 ...

  3. Java中Map的三种遍历方法

    Map的三种遍历方法: 1. 使用keySet遍历,while循环: 2. 使用entrySet遍历,while循环: 3. 使用for循环遍历.   告诉您们一个小秘密: (下↓面是测试代码,最爱看 ...

  4. Jquery中each的三种遍历方法

    Jquery中each的三种遍历方法 $.post("urladdr", { "data" : "data" }, function(dat ...

  5. spring与mybatis三种整合方法

    spring与mybatis三种整合方法 本文主要介绍Spring与Mybatis三种常用整合方法,需要的整合架包是mybatis-spring.jar,可通过链接 http://code.googl ...

  6. C#使用DataSet Datatable更新数据库的三种实现方法

    本文以实例形式讲述了使用DataSet Datatable更新数据库的三种实现方法,包括CommandBuilder 方法.DataAdapter 更新数据源以及使用sql语句更新.分享给大家供大家参 ...

  7. struts2拦截器interceptor的三种配置方法

    1.struts2拦截器interceptor的三种配置方法 方法1. 普通配置法 <struts> <package name="struts2" extend ...

  8. selenium webdriver三种等待方法

    webdriver三种等待方法 1.使用WebDriverWait from selenium import webdriverfrom selenium.webdriver.common.by im ...

  9. ASP.NET文件上传的三种基本方法

    ASP.NET依托.net framework类库,封装了大量的功能,使得上传文件非常简单,主要有以下三种基本方法. 方法一:用Web控件FileUpload,上传到网站根目录. <form i ...

随机推荐

  1. git,repo学习

    Repo:就是一组git命令的集合,repo init 下载一个分支. repo start 文件名 --all本地传建的另一个代码分支,用于备份作用. 比如:repo start zhao --al ...

  2. MVC的Ajax的异步请求

    MVC的Ajax的异步请求 在这里小写一下MVC的异步请求的一点小总结. 个人认为是有两种的,一种就是跟webform一样的,依旧是使用jQuery的$.get()方法,只是请求地址不同,webfor ...

  3. ffmpeg 编码

    编码可以简单理解为将连续的图片帧转变成视频流的过程.以H264为例给出编码的代码: int InitEncoderCodec(int width, int height) { auto enc = a ...

  4. mysql Host ‘XXXXXX’ is blocked because of many connection errors

    mysql Host ‘XXXXXX’ is blocked because of many connection errors ERROR 1129 (00000): Host ‘XXXXXX’ i ...

  5. shell dev null 是什么

    1:在不想把标准输出和标准出错信息输出到控制台,也不想重定向到文件时经常使用 2:不能忽略其读入功能.从/dev/null读入时都是0 3:系统的垃圾桶,类似于Windows的回收站,不同的是这个设备 ...

  6. html——a标签添加点击事件,火狐浏览器直接显示0

    一.问题描述 给一个a标签添加了点击事件,页面直接给了0如下图 二.问题解决 后台调试模式下,发现也进了后台方法,也返回了页面. 于是想到先把页面里大部分内容去掉,去掉所有js,查看是否是部分代码有问 ...

  7. linux杀掉80端口线程命令

    80端口被其他程序占用, fuser -k -n tcp 80

  8. 01-04-01【Nhibernate (版本3.3.1.4000) 出入江湖】原生的SQL查询

    Nhibernate 支持原生的SQL查询 : /// <summary> /// 使用原生的SQL查询 /// </summary> /// <param name=& ...

  9. Implicitly Typed Local Variables

    Implicitly Typed Local Variables It happens time and time again: I’ll be at a game jam, mentoring st ...

  10. POJ2004 Mix and build Trie树? dp?

    学习Trie树中,所以上网搜一下Trie树的题,找到这个,人家写着是简单dp,那我就想着能学习到什么Trie树上的dp,但最后发现根本好像跟Trie树没有什么联系嘛... 题意就是给你很多个字符串(长 ...