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月前
|
C# UED
41.C#:Timer控件
41.C#:Timer控件
14 1
C#编程-46:Timer控件复习笔记
C#编程-46:Timer控件复习笔记
|
消息中间件 Java C#
C# 三个Timer
C# 三个Timer
232 0
C# 三个Timer
|
Java
C# WinForm多线程开发(二) ThreadPool 与 Timer
原文地址:点击打开链接 [摘要]本文介绍C# WinForm多线程开发之ThreadPool 与 Timer,并提供详细的示例代码供参考。 本文接上文,继续探讨WinForm中的多线程问题,再次主要探讨threadpool 和timer。 一 、ThreadPool 线程池(ThreadPool)是一种相对较简单的方法,它适应于一些需要多个线程而又较短任务(如一些常
1493 0
|
Java
C# WinForm多线程开发(二) ThreadPool 与 Timer
原文地址:点击打开链接 [摘要]本文介绍C# WinForm多线程开发之ThreadPool 与 Timer,并提供详细的示例代码供参考。 本文接上文,继续探讨WinForm中的多线程问题,再次主要探讨threadpool 和timer。 一 、ThreadPool 线程池(ThreadPool)是一种相对较简单的方法,它适应于一些需要多个线程而又较短任务(如一些常
1440 0
|
C# Windows
C# Timer用法及实例详解
1.C# Timer用法及实例详解 http://developer.51cto.com/art/200909/149829.htm http://www.cnblogs.com/OpenCoder/archive/2010/02/23/1672043.
1861 0
|
C#
c# 使用timer定时器操作,上次定时到了以后,下次还未执行完怎么处理
c# 使用timer定时器操作,下次定时到了以后,上次还未执行完怎么办 ------解决方案--------------------------------------------------------开始的时候,禁用定时器,你可以在执行完毕之后再启用定时器   定时器定时执行某一个方法时,可能由于执行的时间长要比间隔的时间长,则这种情况可能导致线程并发性的问题。
1832 0