Timer类:

在设定的间隔之后生成事件,带有生成重复事件的选项。

若要浏览此类型的 .NET Framework 源代码,请参阅引用源。

命名空间:                   System.Timers
程序集:         System(位于 System.dll)

继承层次结构

System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Timers.Timer

语法:

[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]public class Timer : Component, ISupportInitialize

构造函数

名称 说明
Timer()

初始化 Timer 类的新实例,并将所有属性设置为初始值。

Timer(Double)

初始化 Timer 类的新实例,并将 Interval 属性设置为指定的毫秒数。

属性

名称 说明
AutoReset

获取或设置一个布尔值,该值指示 Timer 是否应只引发一次 Elapsed 事件((false) 或重复 (true))。

CanRaiseEvents

获取一个值,该值指示组件是否可以引发一个事件。(继承自 Component。)

Container

获取 IContainer ,其中包含 Component。(继承自 Component。)

DesignMode

获取一个值,该值指示是否 Component 当前处于设计模式。(继承自 Component。)

Enabled

获取或设置一个值,该值指示 Timer 是否应引发 Elapsed 事件。

Events

获取的事件处理程序附加到此列表 Component。(继承自 Component。)

Interval

获取或设置引发 Elapsed 事件的间隔(以毫秒为单位)。

Site

此 API 支持 产品 基础结构,不应从代码直接使用。      获取或设置在设计模式中将 Timer 绑定到其容器的站点。(覆盖 Component.Site。)

SynchronizingObject

获取或设置对象,该对象用于在间隔过后封送发出的事件处理程序调用。

方法

名称 说明
BeginInit()

开始用于窗体或由其他组件使用的 Timer 的运行时初始化。

Close()

释放由 Timer 占用的资源。

CreateObjRef(Type)

创建包含生成用来与远程对象通信的代理所需的所有相关信息的对象。(继承自 MarshalByRefObject。)

Dispose()

释放由 Component 使用的所有资源。(继承自 Component。)

Dispose(Boolean)

此 API 支持 产品 基础结构,不应从代码直接使用。      释放由当前 Timer 使用的所有资源。(覆盖 Component.Dispose(Boolean)。)

EndInit()

结束用于窗体或由其他组件使用的 Timer 的运行时初始化。

Equals(Object)

确定指定的对象是否等于当前对象。(继承自 Object。)

Finalize()

在通过垃圾回收将 Component 回收之前,释放非托管资源并执行其他清理操作。(继承自 Component。)

GetHashCode()

作为默认哈希函数。(继承自 Object。)

GetLifetimeService()

检索当前生存期的服务对象,用于控制此实例的生存期策略。(继承自 MarshalByRefObject。)

GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。(继承自 Component。)

GetType()

获取当前实例的 Type。(继承自 Object。)

InitializeLifetimeService()

获取使用生存期服务对象来控制此实例的生存期策略。(继承自 MarshalByRefObject。)

MemberwiseClone()

创建当前 Object 的浅表副本。(继承自 Object。)

MemberwiseClone(Boolean)

创建当前的浅表副本 MarshalByRefObject 对象。(继承自 MarshalByRefObject。)

Start()

通过将 Enabled 设置为 true 开始引发 Elapsed 事件。

Stop()

通过将 Enabled 设置为 false 停止引发 Elapsed 事件。

ToString()

返回 String 包含名称的 Component, ,如果有的话。 不应重写此方法。(继承自 Component。)

事件

名称 说明
Disposed

通过调用释放组件时发生 Dispose 方法。(继承自 Component。)

Elapsed

达到间隔时发生。

备注

说明

To view the .NET Framework source code for this type, see the Reference Sourcehttp://referencesource.microsoft.com/#System/services/timers/system/timers/Timer.cs#897683f27faba082. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructionshttp://referencesource.microsoft.com/.

The T:System.Timers.Timer component is a server-based timer that raises an E:System.Timers.Timer.Elapsed event in your application after the number of milliseconds in the P:System.Timers.Timer.Interval property has elapsed. You can configure the T:System.Timers.Timer object to raise the event just once or repeatedly using the P:System.Timers.Timer.AutoReset property. Typically, a T:System.Timers.Timer object is declared at the class level so that it stays in scope as long as it is needed. You can then handle its E:System.Timers.Timer.Elapsed event to provide regular processing. For example, suppose you have a critical server that must be kept running 24 hours a day, 7 days a week. You could create a service that uses a T:System.Timers.Timer object to periodically check the server and ensure that the system is up and running. If the system is not responding, the service could attempt to restart the server or notify an administrator.

重要事项

The T:System.Timers.Timer class is available in the .NET Framework only. It is not included in the .NET Standard Library and is not available on other platforms, such as .NET Core or the Universal Windows Platform. On these platforms, as well as for portability across all .NET platforms, you should use the T:System.Threading.Timer class instead.

This type implements the T:System.IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its M:System.IDisposable.Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the “Using an Object that Implements IDisposable” section in the T:System.IDisposable interface topic.

The server-based T:System.Timers.Timer class is designed for use with worker threads in a multithreaded environment. Server timers can move among threads to handle the raised E:System.Timers.Timer.Elapsed event, resulting in more accuracy than Windows timers in raising the event on time.

The T:System.Timers.Timer component raises the E:System.Timers.Timer.Elapsed event, based on the value (in milliseconds) of the P:System.Timers.Timer.Interval property. You can handle this event to perform the processing you need. For example, suppose that you have an online sales application that continuously posts sales orders to a database. The service that compiles the instructions for shipping operates on a batch of orders rather than processing each order individually. You could use a T:System.Timers.Timer to start the batch processing every 30 minutes.

重要事项

The System.Timers.Timer class has the same resolution as the system clock. This means that the E:System.Timers.Timer.Elapsed event will fire at an interval defined by the resolution of the system clock if the P:System.Timers.Timer.Interval property is less than the resolution of the system clock. For more information, see the P:System.Timers.Timer.Interval property.

When P:System.Timers.Timer.AutoReset is set to false, a T:System.Timers.Timer object raises the E:System.Timers.Timer.Elapsed event only once, after the first P:System.Timers.Timer.Interval has elapsed. To keep raising the E:System.Timers.Timer.Elapsed event regularly at the interval defined by the P:System.Timers.Timer.Interval, set P:System.Timers.Timer.AutoReset to true, which is the default value.

The T:System.Timers.Timer component catches and suppresses all exceptions thrown by event handlers for the E:System.Timers.Timer.Elapsed event. This behavior is subject to change in future releases of the .NET Framework. Note, however, that this is not true of event handlers that execute asynchronously and include the await operator (in C#)  or the Await operator (in Visual Basic). Exceptions thrown in these event handlers are propagated back to the calling thread, as the following example illustrates. For more information on exceptions thrown in asynchronous methods, see   Exception Handling (Task Parallel Library)【任务并行库】.

using System;using System.Threading.Tasks;using System.Timers;class Example
{   static void Main(){Timer timer = new Timer(1000);timer.Elapsed += async ( sender, e ) => await HandleTimer();timer.Start();Console.Write("Press any key to exit... ");Console.ReadKey();}   private static Task HandleTimer(){Console.WriteLine("\nHandler not implemented..." );    throw new NotImplementedException();}
}
// The example displays output like the following:
//   Press any key to exit...
//   Handler not implemented...
//
//   Unhandled Exception: System.NotImplementedException: The method or operation is
not implemented.
//      at Example.HandleTimer()//      at Example.<<Main>b__0>d__2.MoveNext()
//   --- End of stack trace from previous location where exception was thrown ---
//      at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c__DisplayClass
2.<ThrowAsync>b__5(Object state)
//      at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
//      at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback, Object state, Boolean preserveSyncCtx)
//      at System.Threading.QueueUserWorkItemCallback.System.Threading.
IThreadPoolWorkItem.ExecuteWorkItem()
//      at System.Threading.ThreadPoolWorkQueue.Dispatch()

If the P:System.Timers.Timer.SynchronizingObject property is null, the E:System.Timers.Timer.Elapsed event is raised on a T:System.Threading.ThreadPool thread. If processing of the E:System.Timers.Timer.Elapsed event lasts longer than P:System.Timers.Timer.Interval, the event might be raised again on another T:System.Threading.ThreadPool thread. In this situation, the event handler should be reentrant【凹角,再进入】.

说明:

The event-handling method might run on one thread at the same time that another thread calls the M:System.Timers.Timer.Stop method or sets the P:System.Timers.Timer.Enabled property to false. This might result in the E:System.Timers.Timer.Elapsed event being raised after the timer is stopped. The example code for the M:System.Timers.Timer.Stop method shows one way to avoid this race condition.

Even if P:System.Timers.Timer.SynchronizingObject is not null, E:System.Timers.Timer.Elapsed events can occur after the Overload:System.Timers.Timer.Dispose or M:System.Timers.Timer.Stop method has been called or after the P:System.Timers.Timer.Enabled property has been set to false, because the signal to raise the E:System.Timers.Timer.Elapsed event is always queued for execution on a thread pool thread. One way to resolve this race condition is to set a flag that tells the event handler for the E:System.Timers.Timer.Elapsed event to ignore subsequent events.

If you use the T:System.Timers.Timer class with a user interface element, such as a form or control, without placing the timer on that user interface element, assign the form or control that contains the T:System.Timers.Timer to the P:System.Timers.Timer.SynchronizingObject property, so that the event is marshaled to the user interface thread.

For a list of default property values for an instance of T:System.Timers.Timer, see the M:System.Timers.Timer.#ctor constructor.

Be aware that the .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:

  • System.Timers.Timer (this topic): fires an event at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

  • System.Threading.Timer: executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

  • System.Windows.Forms.Timer: a Windows Forms component that fires an event at regular intervals. The component has no user interface and is designed for use in a single-threaded environment.

  • System.Web.UI.Timer: an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

The following example instantiates a System.Timers.Timer object that fires its E:System.Timers.Timer.Elapsed event every two seconds (2,000 milliseconds), sets up an event handler for the  event, and starts the timer. The event handler displays the value of the P:System.Timers.ElapsedEventArgs.SignalTime property each time it is raised.

using System;using System.Timers;public class Example
{   private static System.Timers.Timer aTimer;   public static void Main(){SetTimer();Console.WriteLine("\nPress the Enter key to exit the application...\n");Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now);Console.ReadLine();aTimer.Stop();aTimer.Dispose();Console.WriteLine("Terminating the application...");}   private static void SetTimer(){       // Create a timer with a two second interval.aTimer = new System.Timers.Timer(2000);       // Hook up the Elapsed event for the timer. aTimer.Elapsed += OnTimedEvent;aTimer.AutoReset = true;aTimer.Enabled = true;}    private static void OnTimedEvent(Object source, ElapsedEventArgs e){Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",e.SignalTime);}
}// The example displays output like the following:
//       Press the Enter key to exit the application...
//
//       The application started at 09:40:29.068
//       The Elapsed event was raised at 09:40:31.084
//       The Elapsed event was raised at 09:40:33.100
//       The Elapsed event was raised at 09:40:35.100
//       The Elapsed event was raised at 09:40:37.116
//       The Elapsed event was raised at 09:40:39.116
//       The Elapsed event was raised at 09:40:41.117
//       The Elapsed event was raised at 09:40:43.132
//       The Elapsed event was raised at 09:40:45.133
//       The Elapsed event was raised at 09:40:47.148
//
//       Terminating the application...

备注:转自https://msdn.microsoft.com/zh-cn/library/system.timers.timer(v=vs.110).aspx

转载于:https://blog.51cto.com/jiaojusuimu/1882669

C#学习常用类(1003)---Timer类(System.Timers.Timer)相关推荐

  1. System.Windows.Forms.Timer与System.Timers.Timer的区别

    .NET Framework里面提供了三种Timer: System.Windows.Forms.Timer System.Timers.Timer System.Threading.Timer VS ...

  2. System.Timers.Timer与System.Threading.Timer

    我最近一直在查看一些可能的计时器,而Threading.Timer和Timers.Timer对我来说是必要的(因为它们支持线程池). 我正在制作游戏,我计划使用不同类型的活动,间隔不同等. 哪个最好? ...

  3. System.Timers.Timer 多线程问题[转]

    已解决问题] System.Timers.Timer 多线程 ,同时首次进 声明: System.Timers.Timer timer = new System.Timers.Timer(); tim ...

  4. [C#]System.Timers.Timer

    摘要 在.Net中有几种定时器,最喜欢用的是System.Timers命名空间下的定时器,使用起来比较简单,作为定时任务,有Quartz.net,但有时候,一个非常简单的任务,不想引入这个定时任务框架 ...

  5. 使用System.Timers.Timer类实现程序定时执行

    在C#里关于定时器类有3个:System.Windows.Forms.Timer类.System.Threading.Timer类和System.Timers.Timer类. System.Windo ...

  6. System.Timers.Timer 嵌套 System.Windows.Forms.Timer的问题

    如题"System.Timers.Timer 嵌套 System.Windows.Forms.Timer的问题",最近在项目中在类uc_Map中启用了System.Timers.T ...

  7. System.Timers.Timer的Enable、Start、Stop记录

    Timer的初始化,此时不执行theout3方法 System.Timers.Timer time = new System.Timers.Timer(); time.Interval = 1000; ...

  8. C# System.Timers.Timer中的坑,程序异常退出后timer依然运行问题

    C# System.Timers.Timer中的坑,程序异常退出后timer依然运行问题 参考文章: (1)C# System.Timers.Timer中的坑,程序异常退出后timer依然运行问题 ( ...

  9. 在System.Timers.Timer的处理程序中调用MessageBox.Show()弹出的确是非模态的

    MessageBox.Show()不应该都是模态的么?但是我在System.Timers.Timer的处理程序中调用MessageBox.Show()弹出的确是非模态的

最新文章

  1. 【Codeforces】53D Physical Education (有点像冒泡)
  2. 《跃迁 从技术到管理的硅谷路径》读后感
  3. hadoop简单介绍_Hadoop:简单介绍
  4. nignx解决vue部署服务器刷新页面出现404问题
  5. 新装Ubuntu 11.04有感
  6. 汇编语言上机考试三星题——根据键盘输入调用子程序显示子程序的入口地址
  7. 如何让普通人了解网络隐私的重要性
  8. python数据爬虫项目
  9. DFA(deterministic finite automaton )有限状态机概念
  10. Unity实战篇 |制作一个跟随鼠标转向的 简易箭头指示标,包括 UI指向 和 3D指向标
  11. swift4.0 涂鸦画板
  12. GitBook入门(用github做出第一本书)——超详细配图说明
  13. [转帖]谨防(练拳时)膝关节损伤十一要
  14. java 蓝牙打印_Android蓝牙打印机,带你真正了解各种打印格式
  15. 文件压缩算法详细分析(ZIP)及解压实例解释
  16. textarea标签 禁止拉伸
  17. c++ 递归算法求全排列
  18. 由于无法验证发布者,Windows已经阻止此软件
  19. MAC如何安装pfx
  20. 设计模式之Facade

热门文章

  1. 计算机工作在原理课件,滇人版七年级信息技术下册第一单元第一课第三课时计算机工作原理.ppt...
  2. ui li 菜单 点击添加下级_如何制作导航栏中的下拉菜单
  3. Spring Boot学习
  4. linux下的tuxedo开发实例
  5. Swift NSDate的一个分类,把Mon Apr 04 19:45:37 +0800 2016这种格式的时间转换为2016-04-04 11:45:37 +0000
  6. css中em单位和rem单位
  7. 【源码小记】jQueryの事件绑定
  8. Bash-Script
  9. Hadoop MapReduce编程 API入门系列之join(二十六)
  10. JZOJ.5274【NOIP2017模拟8.14】数组