.NET BCL 提供了3种Timer
控件:System.Threading.Timer
, System.Timers.Timer
这两种控件都没用过,其中System.Timers.Timer
可以用于UI 线程或者工作线程。
第3种是System.Windows.Forms.Timer
,工具箱里显眼的位置可以看到。不同于VC++,Timer
控件不在Form上,而在Form下方,仔细看才会发现, 双击Timer
控件就会自动生成名称为 timerName_Tick 的方法。
System.Windows.Forms.Timer
的用法:
using System.Windows.Forms;
// namespace
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent(); // 这条语句是IDE自动生的
timer1.Interval = 1000; // 设置时间间隔为1000ms,默认为100ms
timer1.Start(); // 启动计时器, 默认不启动
}
private void timer1_Tick(object sender, EventArgs e)
{
if (timer1.Equals(timer2)) // 判断两个Timer是否相同,这语句没什么用
;
else
{
timer1.Stop();
MessageBox.Show("two timers are not equal.");
Close(); // 最后关闭窗口
}
}
}
timer1.Stop();
不能放在MessageBox
后面,因为这里的 MessageBox
有一个 确定按钮,如果不点击,timer1
持续运行,会持续地弹出对话框, 所以timer1.Stop();
放在前面。
设置属性Enabled = true
完全等同于调用Start()
方法, 同理设置Enable = false
完全等同于调用Stop()
,没有区别。
MSDN: Calling the Start method is the same as setting Enabled to true. Likewise, calling the Stop method is the same as setting Enabled to false.
[1] https://stackoverflow.com/questions/1012948/using-system-windows-forms-timer-start-stop-versus-enabled-true-false
[2] Illustrated C# 7