C# TimerCallBack的使用

本文深入探讨了C#中两种常见的计时器实现方式:System.Windows.Forms.Timer控件和System.Threading.Timer。文章详细介绍了这两种计时器的使用方法、参数设置及其实现原理,并通过实例代码展示了如何在实际项目中应用它们。

刚写C#时,使用Timer比较多的是System.Windows.Forms.Timer。这个控件使用起来比较简单一些,它直接继承自Component。在使用时,TImer控件绑定Tick时间,开始计时采用Timer.Start()或者TImer.enable=True后才会自定计时,停止时候采用TImer.stop()或者Timer.enable=false。在开始之前,需要设置一下Timer.Interval=100(时间间隔ms)。Timer控件和它所在的Form属于同一个线程,因此执行效率不是很高,不如新开一个线程采用system.Threading.Timer。

using System;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication13
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Interval = 1000;
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            textBox1.Text = DateTime.Now.ToShortDateString();
        }
    }
}


System.Threading.Timer  定义该类时,主要有四个参数:

  • 需要回调的对象
  • 要传入给委托的参数,null表示没有参数
  • 延时多久开始执行
  • 每隔几秒执行一次
        public void TestTimerCallBack()
        {
            TimerCallback tc = new TimerCallback((o) => { MessageBox.Show("Do something"); });
            System.Threading.Timer t = new System.Threading.Timer(tc, null, 0, 1000);
        }

再加入一个比较经典的用法:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace TimerApp
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("***** Working with Timer type *****/n");

      // Create the delegate for the Timer type.
      TimerCallback timeCB = new TimerCallback(PrintTime);

      // Establish timer settings.
      Timer t = new Timer(
        timeCB,             // The TimerCallback delegate type.
        "Hello From Main",  // Any info to pass into the called method (null for no info).
        0,                  // Amount of time to wait before starting.
        1000);   //一秒钟调用一次 Interval of time between calls (in milliseconds).

      Console.WriteLine("Hit key to terminate...");
      Console.ReadLine();
    }

    static void PrintTime(object state)
    {
      Console.WriteLine("Time is: {0}, Param is: {1}",
        DateTime.Now.ToLongTimeString(), state.ToString());
    }
  }
}

 

转载于:https://www.cnblogs.com/Kyle-Study/p/10173497.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值