首页 > 编程语言 >C#三种定时器Timer详解

C#三种定时器Timer详解

时间:2023-07-08 18:33:35浏览次数:44  
标签:定时器 C# void object System Timer private using

https://blog.csdn.net/qq_57798018/article/details/128243618

在C#中Timer类的定义有三个:

System.Threading.Timer
System.Windows.Forms.Timer //仅在.NetFramework中
System.Timers.Timer
1、 System.Windows.Forms.Timer定时器
System.Windows.Forms 命名空间下的Timer控件,它直接继承自Componet。Timer控件只有绑定了Tick事件和设置Enabled=True后才会自动计时,停止计时可以用Stop()方法控制,通过Stop()停止之后,如果想重新计时,可以用Start()方法来启动计时器。Timer控件和它所在的Form属于同一个线程;

Enabled:设置或获取定时器是否运行。

Interval:设置时间间隔,单位毫秒,默认为100毫秒。

Start:开启定时器,内部对Enabled设置为true。

Stop:停止定时器,内部对Enabled设置为false。

Tick:当到达Interval时间间隔后触发的事件。

timer1.Enabled = true;
timer1.Interval= 100; //设置时间间隔(毫秒为单位)单位Ms
timer1.Start();
timer1.Stop();


private void timer1_Tick(object sender, EventArgs e)
{
//用户代码
}

实例化1:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Timer1
{
public partial class Form1 : Form
{
public int systemCounter = 0;
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
//设置Timer1控件可用
this.timer1.Enabled = false;
//设置Timer1 时间间隔
this.timer1.Interval = 1000;
}

private void btnStart_Click(object sender, EventArgs e)
{
this.timer1.Start();
}

private void btnStop_Click(object sender, EventArgs e)
{
this.timer1.Stop();
}

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

2、 System.Timers.Timer
System.Timers.Timer类:定义一个System.Timers.Timer对象,然后绑定Elapsed事件,通过Start()方法来启动计时,通过Stop()方法或者Enable=false停止计时。AutoReset属性设置是否重复计时。Elapsed事件绑定相当于另开了一个线程,也就是说在Elapsed绑定的事件里不能访问其它线程里的控件(需要定义委托,通过Invoke调用委托访问其它线程里面的控件)。适用于作为基于服务器的使用或在多线程环境。

AutoReset:自动重置,默认为值true,true表示每次间隔结束后都会引发一次Elapsed事件,false表示仅在首次时间间隔后引发一次Elapsed事件。

Intervel:获取两次Elapsed事件的时间间隔,以毫秒为单位,默认值为100毫秒。

Start:启动定时器。

Stop:停止定时器。

Elapsed:时间间隔后触发的时间。

实例化2:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Timer1
{
public partial class Form1 : Form
{
//定义全局变量
public int systemCounter = 0;
//定义Timer类
System.Timers.Timer timer;
//定义委托
public delegate void SetControlValue(string value);
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
InitTimer();
}
/// <summary>
/// 初始化Timer控件
/// </summary>
private void InitTimer()
{
//设置定时间隔(毫秒为单位)
int interval = 1000;
timer = new System.Timers.Timer(interval);
//设置执行一次(false)还是一直执行(true)
timer.AutoReset = true;
//设置是否执行System.Timers.Timer.Elapsed事件
timer.Enabled = true;
//绑定Elapsed事件
timer.Elapsed += new System.Timers.ElapsedEventHandler(TimerUp);
}
/// <summary>
/// Timer类执行定时到点事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TimerUp(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
systemCounter += 1;
this.Invoke(new SetControlValue(SetTextBoxText), systemCounter.ToString());
}
catch (Exception ex)
{
MessageBox.Show("定时事件失败:" + ex.Message);
}
}
/// <summary>
/// 更新文本框的值
/// </summary>
/// <param name="strValue"></param>
private void SetTextBoxText(string strValue)
{
this.textBox1.Text = this.systemCounter.ToString().Trim();
}
private void btnStart_Click(object sender, EventArgs e)
{
timer.Start();
}

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

}
}

3、System.Threading.Timer

System.Threading.Timer,默认是在线程池线程中引发事件,基于服务器或服务组件在多线程环境中使用。互操作性差,适用于长期执行不进行任何改动的定时任务。可以设置首次延时时间。

实例化3:


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

namespace Threading_Timer
{
public partial class Form1 : Form
{
//定义全局变量
public int systemCounter = 0;
//定义Timer类
System.Threading.Timer threadTimer;
//定义委托
public delegate void SetControlValue(object value);

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
InitTimer();
}
/// <summary>
/// 初始化Timer类
/// </summary>
private void InitTimer()
{
threadTimer = new System.Threading.Timer(new TimerCallback(TimerUp), null, Timeout.Infinite, 1000);
}
/// <summary>
/// 定时到点执行的事件
/// </summary>
/// <param name="value"></param>
private void TimerUp(object value)
{
systemCounter += 1;
this.Invoke(new SetControlValue(SetTextBoxValue), systemCounter);
}
/// <summary>
/// 给文本框赋值
/// </summary>
/// <param name="value"></param>
private void SetTextBoxValue(object value)
{
this.textBox1.Text = value.ToString();
}

private void button1_Click(object sender, EventArgs e)
{
//立即开始计时,时间间隔1000毫秒
threadTimer.Change(0, 1000);
}

private void button2_Click(object sender, EventArgs e)
{
//停止计时
threadTimer.Change(Timeout.Infinite, 1000);
}
}
}
总结:第一种计时器和它所在的Form处于同一个线程,因此执行的效率不高;而第二种和第三种计时器执行的方法都是新开一个线程,所以执行效率比第一种计时器要好,而第三种互操作性差,且容易出错,所以我们在应用定时器时,一般都会选择第二种。
————————————————
版权声明:本文为CSDN博主「微雨夏凉」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_57798018/article/details/128243618

标签:定时器,C#,void,object,System,Timer,private,using
From: https://www.cnblogs.com/Dongmy/p/17537638.html

相关文章

  • 用 AIGC 重构后的智能客服,能否淘到大模型时代的第一桶金?
    ChatGPT的诞生打响了现代AI军备竞赛的第一枪。以GPT-4、ChatGTP、Bard等为代表的大语言模型在全球各界引起了广泛关注。结合ChatGPT的底层技术逻辑,未来中短期内ChatGPT产业化的方向大致有四类:即智能客服、文字模态的AIGC应用、代码开发相关工作以及图像生成。其中,最适......
  • 【Semantic Kernel】4、记忆(Memory)
    为什么需要MemoryLLM对自然语言的理解和掌握在知识内容的解读和总结方面提供了强大的能力。但是由于训练数据本身来自于公共领域,也就注定了无法在一些小众或者私有的领域能够足够的好的应答。因此如何给LLM提供足够多的信息上下文,就是如今的LLMAI应用可以充分发挥能力的地方......
  • error NU1803: 错误形式的警告: 正在通过 “HTTP” 源“http://apricot.com/repositor
    一、私有仓库错误(vs2022)错误信息errorNU1803:错误形式的警告:正在通过“HTTP”源“http://apricot.com/repository/nuget-group/”运行“restore”操作。将来的版本中将删除非HTTPS访问权限。请考虑迁移到“HTTPS”源。错误截图二、解决&处理打开Nuget配置%APP......
  • ihHS-Numerical test report
       ......
  • WINUI 引入 CommunityToolkit.WinUI.UI进行数据验证
     先在xaml命名空间中引入  xmlns:ui="using:CommunityToolkit.WinUI.UI"textbox中进行IP验证如下:<TextBoxx:Name="textBox"Width="200"Height="30"Background="AliceBlue"ui:TextBoxExten......
  • COMP9311 SQL语言
    ThisprojectaimstogiveyoupracticeinReadingandunderstandingamoderatelylargerelationalschema(MyMyUNSW).ImplementingSQLqueriesandviewstosatisfyrequestsforinformation.ImplementingPL/pgSQLfunctionstoaidinsatisfyingrequestsforin......
  • 阵列信号处理及matlab仿真-------波束形成算法基础知识以及MMSE、MSNR和LCMV的MATLAB
    上一篇《阵列信号处理及MATLAB仿真-----阵列信号绪论》里面说了阵列信号处理研究的四个主要问题:波束形成技术、空间谱估计、信号源定位、信源分离。接下来我们就波束形成来做一个详细的学习。一、波束形成的定义:首先说一下它的物理意义,阵列天线的方向图是全方向的,但是......
  • OpenCV计算机视觉学习(14)——浅谈常见图像后缀(png, jpg, bmp)的区别(opencv读取语义分割m
    如果需要处理的原图及代码,请移步小编的GitHub地址传送门:请点击我如果点击有误:https://github.com/LeBron-Jian/ComputerVisionPractice 本来不想碎碎念,但是我已经在图像后缀上栽倒两次了。而且因为无意犯错,根本找不到问题。不论是在深度学习的语义分割中,还是在图......
  • Codeforces Round 883 (Div. 3)
    CodeforcesRound883(Div.3)A.RudolphandCuttheRope:题意:有一个糖果由n个绳子悬挂,告诉每一个绳子位于的高度和宽度,问至少间断几根才可以让candy回到groud。思路:统计有几个宽度小于高度的绳子即可voidsolve(){intn;intnum=0;cin>>n;for(inti=1;i......
  • XXI Opencup, Grand Prix of Korea
    目录XXIOpencup,GrandPrixofKoreaADHKJFIEGXXIOpencup,GrandPrixofKoreaOpenCup强度这么大吗(A根据Hall定理,把\(a\)从大到小排序对于\(\forallx\in[1,n]\)如果有\(\sum_{i=1}^xa_i\leq\sum_{i=1}^m\min\{x,b_i\}\)则等价于可以分发完全。......