几点说明 由于正在做的一个小项目需要使用计时的功能,所以有了这个Timer使用的文章

这篇的内容主要参考自MSDN中有关Timer使用的说明

以后如果遇到更高层次的使用方法,会继续更新这篇文章

来自MSDN的说明System.Timers.Timer Name Description

Method Timer

「构造方法」 Initializes a new instance of the Timer class, and sets all the properties to their initial values.

初始化一个Timer类的新实例,以及设置初始值,精确度为秒。

Method Timer(Double)

「构造方法」 Initializes a new instance of the Timer class, and sets the Interval property to the specified number of milliseconds.

初始化一个Timer类的新实例,以及设置初始值,精确度为毫秒。

Property AutoReset

「自动重置」 Gets or sets a value indicating whether the Timer should raise the Elapsed event each time the specified interval elapses or only after the first time it elapses.

获取或设置一个值指示 Timer 是「每次都调用Elapsed 事件」还是「只有第一次调用」。

Property SynchronizingObject

「同步对象」 Gets or sets the object used to marshal event-handler calls that are issued when an interval has elapsed.

获取或设置用于整理超过设置的时间间隔的事件调用。

Method Start

「Public」 Starts raising the Elapsed event by setting Enabled to true.

通过设置Enalbed为true,马上开始调用Elapsed

Method Stop

「Public」 Stops raising the Elapsed event by setting Enabled to false.

通过设置Enalbed为false,马上停止调用Elapsed

Event Elapsed

「流逝」 Occurs when the interval elapses.

当时间间隔「流逝」时触发。

The Timer component is a server-based timer, which allows you to specify a recurring interval at which the Elapsed event is raised in your application. You can then handle this event to provide regular processing.

Timer组件是一个基于服务器的计时器,它允许你指定一个有间隔的「调用」Elapsed事件的循环。你可以捕获这个事件来进行你的处理。 Note: When AutoReset is set to false, the Timer raises the Elapsed event only once, after the first Interval has elapsed. To keep raising the Elapsed event on the Interval, set AutoReset to true.

当AutoReset属性设置为false时,Timer在第一次时间间隔到了之后,只调用一次Elapsed事件。为了保证每次时间间隔都调用Elapsed事件,要设置AutoReset属性为true If the SynchronizingObject property is Nothing, the Elapsed event is raised on a ThreadPool thread. If processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. In this situation, the event handler should be reentrant.

如果SynchronizingObject 属性没有设置, Elapsed事件被一个线程池线程调用。如果Elapsed事件持续的时间比一次间隔要长,这个事件可能会在另一个线程池的线程被调用。在这种情况下,事件处理应该是可重复的。 Note: The event-handling method might run on one thread at the same time that another thread calls the Stop method or sets the Enabled property to false. This might result in the Elapsed event being raised after the timer is stopped.

当一个线程调用Stop方法或设置Enabled属性为false时,相应的事件处理方法可能会在不同的线程中继续执行。这可能导致Elapsed事件在计时器已经被停止的时候继续执行。 Even if SynchronizingObject is not Nothing, Elapsed events can occur after the Dispose or Stop method has been called or after the Enabled property has been set to false, because the signal to raise the 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 Elapsed event to ignore subsequent events.

即使SynchronizingObject 已经设置了,Elapsed事件还是会发生在Dispose或Stop方法被调用之后或在Enabled属性被设置成false后,因为调用Elapsed事件的「符号」总是在一个线程池中列队执行。一个解决这个竞争条件的方法是设置一个「标识」告诉Elapsed事件处理程序忽略掉随后的事件。

MSDN示例程序using System;

using System.Timers;

public class Timer1

{

private static System.Timers.Timer aTimer;

public static void Main()

{

// Normally, the timer is declared at the class level,

// so that it stays in scope as long as it is needed.

// If the timer is declared in a long-running method,

// KeepAlive must be used to prevent the JIT compiler

// from allowing aggressive garbage collection to occur

// before the method ends. You can experiment with this

// by commenting out the class-level declaration and

// uncommenting the declaration below; then uncomment

// the GC.KeepAlive(aTimer) at the end of the method.

//System.Timers.Timer aTimer;

// Create a timer with a ten second interval.

aTimer = new System.Timers.Timer(10000);

// Hook up the Elapsed event for the timer.

aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

// Set the Interval to 2 seconds (2000 milliseconds).

aTimer.Interval = 2000;

aTimer.Enabled = true;

Console.WriteLine("Press the Enter key to exit the program.");

Console.ReadLine();

// If the timer is declared in a long-running method, use

// KeepAlive to prevent garbage collection from occurring

// before the method ends.

//GC.KeepAlive(aTimer);

}

// Specify what you want to happen when the Elapsed event is

// raised.

private static void OnTimedEvent(object source, ElapsedEventArgs e)

{

Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);

}

}

/* This code example produces output similar to the following:

Press the Enter key to exit the program.

The Elapsed event was raised at 5/20/2007 8:42:27 PM

The Elapsed event was raised at 5/20/2007 8:42:29 PM

The Elapsed event was raised at 5/20/2007 8:42:31 PM

...

*/

个人演示程序

TimerWindow

TimerWindow的XAML内容

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="Timer测试 - http://www.cnblogs.com/sitemanager/" Height="89" Width="287" Loaded="Window_Loaded">

TimerWindow的后台代码using System.Windows;

using System.Timers;

namespace csdemo.wpf.controls.Timer

{

///

/// TimerWindow.xaml 的交互逻辑

///

public partial class TimerWindow : Window

{

public TimerWindow()

{

InitializeComponent();

}

private void btnStart_Click(object sender, RoutedEventArgs e)

{

aTimer.Start();

}

System.Timers.Timer aTimer = new System.Timers.Timer();

static int elapsedTimes;

private void Window_Loaded(object sender, RoutedEventArgs e)

{

aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

aTimer.Interval = 2000; // 1秒 = 1000毫秒

}

///

/// Timer的Elapsed事件处理程序

///

///

///

private static void OnTimedEvent(object source, ElapsedEventArgs e)

{

MessageBox.Show((++elapsedTimes).ToString(), "Timer测试 - http://www.cnblogs.com/sitemanager/");

}

private void btnStop_Click(object sender, RoutedEventArgs e)

{

aTimer.Stop();

MessageBox.Show("Timer已停止,之前共触发次" + (elapsedTimes).ToString() + "事件", "Timer测试 - http://www.cnblogs.com/sitemanager/");

elapsedTimes = 0;

}

private void btnClose_Click(object sender, RoutedEventArgs e)

{

aTimer.Dispose(); // 清理aTimer使用的内存

MessageBox.Show("欢迎使用『峻之岭峰』的WPF控件Demo,您可以在我的博客中看到最新发表的有关编程技术的个人总结。 \n 博客地址: http://www.cnblogs.com/sitemanager/ \n\n如果您是在点击停止之前点击此按钮,将会造成无法停止Timer!\n此时您可以返回您的开发工具停止调试项目。\n或直接在资源管理器中终止进程。\n\n\n 在使用本Demo的同时,由于个人的开发环境不同,所以请不要简单的拷贝代码", "『峻之岭峰』的WPF控件Demo - http://www.cnblogs.com/sitemanager/");

this.Close();

}

}

}

说明:注意之前说过的Timer Elapsed事件的线程有关的问题

注意,你可以在任何你想开始计时的地方调用Timer的Start()方法开始计时,调用Stop()方法停止计时。

运行效果

timer计时 wpf_『WPF』Timer的使用相关推荐

  1. 『WPF』TextBox元素过滤键盘输入

    本文最后更新于 2019年 5月 6号 凌晨 2点 03分,并同步发布于 : 简书 -- 创作你的创作 CSDN -- 专业 IT 技术社区 www.tobinary.art -- 我的博客 在编写 ...

  2. 『WPF』实现拖动文件到窗体(控件)

    前言 实现从窗口外部拖文件到窗口内部并自动捕获文件地址. 第一步 开启属性 启用底层Window的AllowDrop属性,添加Drop事件. Drop事件:当你拖动文件到对应控件后,松开触发. 除Dr ...

  3. WPF的Timer控件的使用

    原文:WPF的Timer控件的使用 通过System.Threaing.Timer控件来实现"初始加载页面时为DataGrid的模版列赋初始值" System.Threaing.T ...

  4. Flash Player帧频、Timer计时 的时间间隔

    对于大部分Flash开发者,都已经知道Flash的帧频.Timer计时并不是十分精确的.如果您已经做过这方面测试,可以略过这篇文章的前面一部分,在后面有关于Flash Player可变跑道的文章链接, ...

  5. 『转载』Debussy快速上手(Verdi相似)

    『转载』Debussy快速上手(Verdi相似) Debussy 是NOVAS Software, Inc(思源科技)发展的HDL Debug & Analysis tool,这套软体主要不是 ...

  6. 『参考』.net CF组件编程(4)——为自定义组件添加工具箱图标!

    前言: 在前三篇的文章中,和大家一起创建了一个用于TCP连接检测的小组件,如果你记不得了,可以通过以下链接去回顾一下: 『参考』.net CF组件编程(1)--基础之后 『参考』.net CF组件编程 ...

  7. 『TensorFlow』命令行参数解析

    argparse很强大,但是我们未必需要使用这么繁杂的东西,TensorFlow自己封装了一个简化版本的解析方式,实际上是对argparse的封装 脚本化调用tensorflow的标准范式: impo ...

  8. 『Numpy』常用方法记录

    numpy教程 防止输出省略号 import numpy as np np.set_printoptions(threshold=np.inf) 广播机制 numpy计算函数返回默认是一维行向量: i ...

  9. 2018年『web』开发者不得不知的技术趋势

    作为一个『web』开发者,无论是做前端还是后端,都应该时刻保持着对技术的敏感性.技术的流行需要一定时间的沉淀,有哪些web相关的技术会可能会在2018年成为web开发的新宠呢?下面列举业界经过实践并且 ...

  10. 『TensorFlow』函数查询列表_张量属性调整

    博客园 首页 新随笔 新文章 联系 订阅 管理 『TensorFlow』函数查询列表_张量属性调整 数据类型转换Casting 操作 描述 tf.string_to_number (string_te ...

最新文章

  1. go interface转int_32. 一篇文章理解 Go 里的函数
  2. (转载)以太网最大帧和最小帧、MTU .
  3. Golang判断元素是否存在数组中
  4. 微信读书android换到ios,Android 微信读书本周推荐传送带列表实现
  5. Spring XD用于数据提取
  6. delay在java中有什么用_java中DelayQueue的使用
  7. C++语言类的继承与派生介绍和示例
  8. linux切换用户无法加载变量,Linux 中用户切换:su 和 su- 的使用 环境变量详解
  9. Python之 if-else
  10. AI、大数据、中台、AIoT、Fintech等十余场火热专题应有尽有,年度盛会BDTC 2019邀您共赴!...
  11. 「倾心整理~」数据库系统概论—第5章(数据库完整性)
  12. 在python中打开文件显示没有权限PermissionError: [Errno 13] Permission denied:
  13. 配置activity-alias别名,更改app图标和名字
  14. 物联网学习之路——物联网通信技术简介
  15. Flash--提高flash的使用寿命(1)
  16. Windows Mobile系统PDA进行GPS导航的入门知识
  17. 读书笔记012:《伤寒论》- 手少阳三焦经
  18. art-template整理
  19. 用python做系统的感悟_python感悟
  20. Log4j2写日志的艺术

热门文章

  1. python pip下载安装一半退出_Python- 解决PIP下载安装时因为网络速度慢而导致失败的方法...
  2. jQuery中文文档(jQuery 3.1 参考手册+jQuery.api.3.2.1)
  3. 得力考勤机excel密码_考勤机
  4. 好看的2020年html倒计时源码
  5. 搭建一个自己的文件上传服务器。
  6. Padavan启用ipv6并允许公网访问内网
  7. 小米路由器r1d刷第三方_好物推荐 篇三:服役多年的小米路由器R1D准备让他退休, 小米路由R3D开始上岗...
  8. 绿盟漏洞扫描工具_IDC盘点2020上半年中国安全市场绿盟科技再获响应和编排能力认可...
  9. 2019美赛D题,元胞自动机模拟游客疏散过程
  10. java 算法 pdf_Java 常用算法手册 PDF扫描版[39MB]