很好,但是为了模拟时间流逝,我们需要运行一个需要一些时间的命令,在第二个示例中这非常清楚。
但是,使用for循环永久执行某些功能的样式占用大量设备资源,相反,我们可以使用垃圾回收器来执行类似的操作。
我们可以在同一本书《 CLR via C#Third Ed》的代码中看到此修改。
using System;
using System.Threading;
public static class Program {
public static void Main() {
// Create a Timer object that kNows to call our TimerCallback
// method once every 2000 milliseconds.
Timer t = new Timer(TimerCallback, null, 0, 2000);
// Wait for the user to hit <Enter>
Console.ReadLine();
}
private static void TimerCallback(Object o) {
// Display the date/time when this method got called.
Console.WriteLine("In TimerCallback: " + DateTime.Now);
// Force a garbage collection to occur for this demo.
GC.Collect();
}
}