首页 > 编程语言 >C# system.Threading.Timer和system.Timers中的定时器

C# system.Threading.Timer和system.Timers中的定时器

时间:2023-07-30 09:45:05浏览次数:41  
标签:C# system timer System Threading Timers Timer 线程

它们都可以用于在指定时间间隔后执行代码。然而,它们在实现和用法上有一些差异。
System.Threading.Timer:
System.Threading.Timer 是基于线程的定时器,它属于 System.Threading 命名空间。它使用 ThreadPool 线程来执行定时操作。以下是关于 System.Threading.Timer 的一些重要特点:

构造函数:Timer(TimerCallback callback, object state, int dueTime, int period)
TimerCallback 是一个委托,它指向要定时执行的方法。state 是传递给回调方法的对象参数。
dueTime 表示创建定时器后首次执行回调方法的延迟时间(以毫秒为单位)。
period 表示回调方法的执行间隔(以毫秒为单位)。如果将其设置为 0,它只会在 dueTime 后执行一次。
示例:

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        TimerCallback callback = DoSomething;
        Timer timer = new Timer(callback, null, 0, 1000);

        Console.WriteLine("Press any key to stop the timer.");
        Console.ReadKey();

        // Dispose the timer to stop it properly.
        timer.Dispose();
    }

    static void DoSomething(object state)
    {
        Console.WriteLine("Doing something...");
    }
}

System.Timers.Timer:
System.Timers.Timer 是基于事件的定时器,它属于 System.Timers 命名空间。它使用基于底层计时器的实现,而不是线程池线程。以下是关于 System.Timers.Timer 的一些重要特点:

构造函数:Timer(double interval)
interval 表示定时器的执行间隔(以毫秒为单位)。
示例:

using System;
using System.Timers;

class Program
{
    static void Main()
    {
        Timer timer = new Timer(1000); // 1 second interval
        timer.Elapsed += Timer_Elapsed;
        timer.Start();

        Console.WriteLine("Press any key to stop the timer.");
        Console.ReadKey();

        timer.Stop();
        timer.Dispose();
    }

    private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("Doing something...");
    }
}

2 / 2

在 C# 中,有两种常用的定时器类,分别是 System.Threading.Timer 和 System.Timers.Timer,它们都可以用于在指定时间间隔后执行代码。然而,它们在实现和用法上有一些差异。

System.Threading.Timer:
System.Threading.Timer 是基于线程的定时器,它属于 System.Threading 命名空间。它使用 ThreadPool 线程来执行定时操作。以下是关于 System.Threading.Timer 的一些重要特点:

构造函数:Timer(TimerCallback callback, object state, int dueTime, int period)
TimerCallback 是一个委托,它指向要定时执行的方法。state 是传递给回调方法的对象参数。
dueTime 表示创建定时器后首次执行回调方法的延迟时间(以毫秒为单位)。
period 表示回调方法的执行间隔(以毫秒为单位)。如果将其设置为 0,它只会在 dueTime 后执行一次。
示例:

csharp
Copy code
using System;
using System.Threading;

class Program
{
static void Main()
{
TimerCallback callback = DoSomething;
Timer timer = new Timer(callback, null, 0, 1000);

    Console.WriteLine("Press any key to stop the timer.");
    Console.ReadKey();

    // Dispose the timer to stop it properly.
    timer.Dispose();
}

static void DoSomething(object state)
{
    Console.WriteLine("Doing something...");
}

}
System.Timers.Timer:
System.Timers.Timer 是基于事件的定时器,它属于 System.Timers 命名空间。它使用基于底层计时器的实现,而不是线程池线程。以下是关于 System.Timers.Timer 的一些重要特点:

构造函数:Timer(double interval)
interval 表示定时器的执行间隔(以毫秒为单位)。
示例:

csharp
Copy code
using System;
using System.Timers;

class Program
{
static void Main()
{
Timer timer = new Timer(1000); // 1 second interval
timer.Elapsed += Timer_Elapsed;
timer.Start();

    Console.WriteLine("Press any key to stop the timer.");
    Console.ReadKey();

    timer.Stop();
    timer.Dispose();
}

private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
    Console.WriteLine("Doing something...");
}

}
差异总结:

实现方式:

System.Threading.Timer 使用 ThreadPool 线程执行定时操作。
System.Timers.Timer 使用基于底层计时器的实现。
精度:

System.Threading.Timer 相对精确,但受到线程池的限制,可能会有轻微的延迟。
System.Timers.Timer 提供更高的精确度。
回调方法:

System.Threading.Timer 使用 TimerCallback 委托来执行回调方法。
System.Timers.Timer 使用事件模型(Elapsed 事件)来执行回调方法。
线程安全性:

System.Threading.Timer 需要开发人员自行处理可能出现的线程同步问题。
System.Timers.Timer 本身是线程安全的,因为它使用了基于事件的模型。
根据需要选择合适的定时器类,如果需要更高的精确度和线程安全性,可以优先考虑 System.Timers.Timer。但请注意,当执行回调方法较为复杂或耗时时,任何定时器都可能受到回调方法本身执行时间的影响,所以在选择定时器时,也要结合实际场景进行评估。

标签:C#,system,timer,System,Threading,Timers,Timer,线程
From: https://www.cnblogs.com/johnyang/p/17591016.html

相关文章

  • abc312c <二分答案>
    题目C-InvisibleHand思路二分X,同时二分得到buyer和seller的人数(很精巧的二分~);当然,从复杂度角度,\(O(N\logN)\)也是可以的;实际上可以写成\(O(N)\)的形式?感觉线性扫描也可?代码点击查看代码#include<iostream>#include<algorithm>#include<vector>#include<cst......
  • GoRedisLock:Golang保障数据一致性的分布式锁解决方案
    在现代分布式系统中,多个节点之间共享资源是常见的需求。然而,并发访问共享资源可能导致数据不一致性和竞争条件。为了解决这些问题,我们需要引入分布式锁。GoRedisLock是一个出色的分布式锁库,它结合了Go语言和Redis的优势,提供了稳定高效的分布式并发控制解决方案。**项目地址:**htt......
  • Your configuration specifies to merge with the ref
    目录Yourconfigurationspecifiestomergewiththeref1.执行gitpull命令时,错误提示:1.1场景:分支名称拼写错误1.1.1场景描述1.1.2产生原因1.1.3解决方案1.2场景:远程端同名分支已被删除1.2.1场景描述1.2.2产生原因1.2.3解决方案1.3场景:其它场景(排除场景1和场景2)1.3.......
  • centos 7 ONBOOT=yes 启动失败
    centos7ONBOOT=yes启动失败 今天在centOS7下更改完静态ip后发现network服务重启不了,翻遍了网络,尝试了各种方法,终于解决了。现把各种解决方法归纳整理,希望能让后面的同学少走点歪路。。。首先看问题:执行servicenetworkrestart命令后出现下面的错误: Restartingnetwo......
  • C语言从入门到绝望
    Aclockinoneline:intmain(int_,char**__){_^448&&main(-~_,__);__builtin_putchar(--_%64?32|-~7[__TIME__-_/8%8][">'txiZ^(~z?"-48]>>";;;====~$::199"[_*2&8|_/64]/(_&2?1:8)%8&1:10);}Hello,World!int......
  • HTML5/CSS3学习——Canvas使用
    什么是Canvas?HTML5的Canvas 元素使用JavaScript在网页上绘制图像。画布是一个矩形区域,你可以控制其每一像素。canvas拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法。 创建Canvas元素向HTML5页面添加Canvas 元素。规定元素的id、宽度和高度:<canvas......
  • wordpress pwnscriptum
    vulhub/wordpress/pwnscriptum/README.zh-cn.mdatmaster·vulhub/vulhub·GitHub(191条消息)漏洞复现-Wordpress4.6PwnScriptumRCE命令执行_wordpressrce_amingMM的博客-CSDN博客1、介绍名称:Wordpress4.6任意命令执行漏洞编号:原理:漏洞缺陷处在后台找回密码的地......
  • 重温C#中的值类型和引用类型
    在C#中,数据类型分为值类型和引用类型两种。引用类型变量存储的是数据的引用,数据存储在数据堆中,而值类型变量直接存储数据。对于引用类型,两个变量可以引用同一个对象。因此,对一个变量的操作可能会影响另一个变量引用的对象。对于值类型,每个变量都有自己的数据副本,并且对一个变量的......
  • VS选择Visual C++中的控制台项目和空项目、Windows桌面应用程序三者之间有什么区别?
    在VisualStudio中创建C/C++项目时,可以选择控制台项目、空项目和Windows桌面应用程序,它们有以下区别:控制台项目(ConsoleApplication):这种项目类型适用于命令行应用程序的开发。它提供一个命令行界面,可以在控制台中进行输入和输出操作,通常用于简单的控制台程序,如计算器、文件......
  • error C1083: 无法打开包括文件:“iostream.h”: No such file or directory
    用VS2010打开VC++6程序,按下F5键会发现有错误提示:errorC1083:无法打开包括文件:“iostream.h”:Nosuchfileordirectory;而程序在VC++6中没有任何问题!主要的原因是:1.#include<iostream.h>是原来的C语言里面的,而#include<iostream>是c++的标准库里的,而要调用这个这个标准库......