C# Timer 定时器应用

简介:         关于C#中timer类 在C#里关于定时器类就有3个:         1.定义在System.Windows.Forms里         2.定义在System.Threading.Timer类里         3.定义在System.Timers.Timer类里         System.Windows.Forms.Timer是应用于WinForm中的,
        关于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定时器的用法。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Timers;
using System.Runtime.InteropServices;
using System.Threading;

namespace Timer001
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
           
        }
        //实例化Timer类
        System.Timers.Timer aTimer = new System.Timers.Timer();      

        private void button1_Click(object sender, EventArgs e)
        {
            this.SetTimerParam();
        }

        private void test(object source, System.Timers.ElapsedEventArgs e)
        {     
            MessageBox.Show(DateTime.Now.ToString());           
        }

        public void SetTimerParam()
        {
            //到时间的时候执行事件
            aTimer.Elapsed += new ElapsedEventHandler(test);
            aTimer.Interval = 1000;
            aTimer.AutoReset = true;//执行一次 false,一直执行true
            //是否执行System.Timers.Timer.Elapsed事件
            aTimer.Enabled = true;
        }
    }
}

实现的效果是:每秒弹出系统当前时间,如下图:


目录
相关文章
|
1月前
定时器
定时器
11 0
|
6月前
用555定时器接成的多谐振荡电路的介绍
用555定时器构建的多谐振荡电路 一、引言 多谐振荡电路是一种能够产生多个频率的振荡信号的电路结构。它在音乐合成器、电子琴等设备中有着广泛的应用。本文将介绍一种使用555定时器构建的多谐振荡电路。 二、555定时器简介 555定时器是一种经典的集成电路,由三个功能单元组成:比较器、RS触发器和放大器。它可以用作脉冲发生器、频率分频器、定时器等。在多谐振荡电路中,我们将利用555定时器的单稳态多谐振荡特性来实现多个频率的振荡。 三、电路设计 1. 电路原理 多谐振荡电路的基本原理是利用555定时器的单稳态多谐振荡特性。单稳态多谐振荡是指当555定时器处于单稳态时,输出信号的频率会随着电容和
172 0
|
4月前
|
C#
[C#] 定时器的使用
[C#] 定时器的使用
17 0
|
9月前
扣奖(定时器)
扣奖(定时器)
33 0
|
前端开发 JavaScript
34、定时器
setTimeout函数用来指定某个函数或某段代码,在多少毫秒之后执行。
125 0
|
消息中间件 Java C#
C# 三个Timer
C# 三个Timer
232 0
C# 三个Timer
2.6.4 Qtimer定时器介绍
2.6.4 Qtimer定时器介绍
105 0
2.6.4 Qtimer定时器介绍
|
C#
C#中的三种定时器总结
C#中的三种定时器总结
330 0
C#中的三种定时器总结