如何將計時器添加到C#控制臺應(yīng)用程序就是這樣 - 如何在C??刂婆_應(yīng)用程序中添加計時器?如果你能提供一些示例編碼會很棒。
3 回答

吃雞游戲
TA貢獻(xiàn)1829條經(jīng)驗 獲得超7個贊
這非常好,但是為了模擬一些時間的流逝,我們需要運行一個需要一些時間的命令,這在第二個例子中非常清楚。
但是,使用for循環(huán)來執(zhí)行某些功能的風(fēng)格永遠(yuǎn)需要大量的設(shè)備資源,而我們可以使用垃圾收集器來做這樣的事情。
我們可以在同一本書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貢獻(xiàn)1839條經(jīng)驗 獲得超15個贊
這是創(chuàng)建簡單的一秒計時器滴答的代碼:
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); } } }
這是結(jié)果輸出:
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
編輯:將硬自旋循環(huán)添加到代碼中永遠(yuǎn)不是一個好主意,因為它們消耗CPU周期而沒有增益。在這種情況下,添加循環(huán)只是為了阻止應(yīng)用程序關(guān)閉,允許觀察線程的操作。但為了正確起見并減少CPU使用,在該循環(huán)中添加了一個簡單的Sleep調(diào)用。
- 3 回答
- 0 關(guān)注
- 921 瀏覽
添加回答
舉報
0/150
提交
取消