如何将计时器添加到C#控制台应用程序就是这样 - 如何在C#控制台应用程序中添加计时器?如果你能提供一些示例编码会很棒。
3 回答
吃鸡游戏
TA贡献1829条经验 获得超7个赞
这非常好,但是为了模拟一些时间的流逝,我们需要运行一个需要一些时间的命令,这在第二个例子中非常清楚。
但是,使用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();
}}
紫衣仙女
TA贡献1839条经验 获得超15个赞
这是创建简单的一秒计时器滴答的代码:
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调用。
- 3 回答
- 0 关注
- 960 浏览
添加回答
举报
0/150
提交
取消
