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

How do you add a timer to a C# console application(如何将计时器添加到 C# 控制台应用程序)
本文介绍了如何将计时器添加到 C# 控制台应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

就是这样 - 如何将计时器添加到 C# 控制台应用程序?如果您能提供一些示例编码,那就太好了.

Just this - How do you add a timer to a C# console application? It would be great if you could supply some example coding.

推荐答案

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

That's very nice, however in order to simulate some time passing we need to run a command that takes some time and that's very clear in second example.

但是,使用 for 循环来执行某些功能的方式永远会占用大量设备资源,而我们可以使用垃圾收集器来执行类似的操作.

However, the style of using a for loop to do some functionality forever takes a lot of device resources and instead we can use the Garbage Collector to do some thing like that.

我们可以在同一本书 CLR Via C# Third Ed 的代码中看到这种修改.

We can see this modification in the code from the same book CLR Via C# Third Ed.

using System;
using System.Threading;

public static class Program 
{
   private Timer _timer = null;
   public static void Main() 
   {
      // Create a Timer object that knows to call our TimerCallback
      // method once every 2000 milliseconds.
      _timer = 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);
   }
}

这篇关于如何将计时器添加到 C# 控制台应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Custom Error Queue Name when using EasyNetQ for RabbitMQ?(使用 EasyNetQ for RabbitMQ 时自定义错误队列名称?)
How to generate password_hash for RabbitMQ Management HTTP API(如何为 RabbitMQ 管理 HTTP API 生成密码哈希)
Rabbitmq Ack or Nack, leaving messages on the queue(Rabbitmq Ack 或 Nack,将消息留在队列中)
Setup RabbitMQ consumer in ASP.NET Core application(在 ASP.NET Core 应用程序中设置 RabbitMQ 消费者)
Specify Publish timeouts in mass transit(指定公共交通中的发布超时)
RabbitMQ asynchronous support(RabbitMQ 异步支持)