您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何将计时器添加到C#控制台应用程序

如何将计时器添加到C#控制台应用程序

很好,但是为了模拟时间流逝,我们需要运行一个需要一些时间的命令,在第二个示例中这非常清楚。

但是,使用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();
   }
}
c# 2022/1/1 18:15:31 有575人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶