猿问
如何将计时器添加到C#控制台应用程序
如何将计时器添加到C#控制台应用程序
就是这样 - 如何在C#控制台应用程序中添加计时器?如果你能提供一些示例编码会很棒。
潇湘沐
浏览 905
回答 3
3回答
吃鸡游戏
这非常好,但是为了模拟一些时间的流逝,我们需要运行一个需要一些时间的命令,这在第二个例子中非常清楚。但是,使用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(); }}
0
0
0
紫衣仙女
这是创建简单的一秒计时器滴答的代码: using System; using System.Threading; class TimerExample { static public void Tick(Object stateInfo) { Console.WriteLine("Tick: {0}", DateTime.Now.ToString("h:mm:ss")); } static void Main() { TimerCallback callback = new TimerCallback(Tick); Console.WriteLine("Creating timer: {0}\n", DateTime.Now.ToString("h:mm:ss")); // create a one second timer tick Timer stateTimer = new Timer(callback, null, 0, 1000); // loop here forever for (; ; ) { // add a sleep for 100 mSec to reduce CPU usage Thread.Sleep(100); } } }这是结果输出: c:\temp>timer.exe Creating timer: 5:22:40 Tick: 5:22:40 Tick: 5:22:41 Tick: 5:22:42 Tick: 5:22:43 Tick: 5:22:44 Tick: 5:22:45 Tick: 5:22:46 Tick: 5:22:47编辑:将硬自旋循环添加到代码中永远不是一个好主意,因为它们消耗CPU周期而没有增益。在这种情况下,添加循环只是为了阻止应用程序关闭,允许观察线程的操作。但为了正确起见并减少CPU使用,在该循环中添加了一个简单的Sleep调用。
0
0
0
随时随地看视频
慕课网APP
相关分类
C#
typedef入门问题
1 回答
我要回答