C# - Timer
Timer
1. System.Windows.Form.Timer
2. System.Threading.Timer
3. System.Timers.Timer
2, 3 两个对象的运行核心都是 System.Threading.ThreadPool(线程池)
Threading.Timer 和 Timers.Timer 区别
threading.Timer | Timers.Timer | |
构造函数 | ||
事件响应设置 |
事件相应不在构造函数中设置 timer.Elapsed += new ElapsedEventHandler(Method) Method(object sender, ElapsedEventArgs e) |
|
开始执行 | 需要手动调用 timer.Start() 或者 timer.Enabled = true | |
停止执行 |
需要手动调用 timer.Stop() 或者 timer.Enabled = false timer.Enabled = false 会取消线程池中当前等待队列中剩余任务的执行. |
|
安全性 | 在线程结束时 比前者安全 |
Timer 创建
//参数: callback 方法, object参数, 延迟开始时间, 重复时间间隔 Timer t = new Timer(new TimerCallback(TestMethod), "param", 0, 2000);
public static void TestMethod(object data) { string datastr = data as string; Console.WriteLine("参数为:{0}", datastr); }