看到CSDN老有人問怎麼去設定定時器,坦白說第一次看到可能不大理會怎麼去實現,但是一而再,再而三的遇到這麼多求知者的目光,我也有種衝動想知道到底是怎麼實現的。雖然也是完全摸不著是怎麼實現,但是總會有一些大蝦講解要用什麼類什麼方法去實現。俗話說得好,師傅領進門,修行還是要看個人的。所以有了思路之後,就是尋找實現你思路的方法,雖然也查看了MSDN(http://msdn.microsoft.com/zh-cn/library/ah1h85ch(VS.95).aspx)的講解,但是坦白說,我的理解能力有問題,還不知道該原始碼是以何種項目方式來運行。
不過好在網上還是有很多這方面的例子的,我找到一個網站是專門給我們這些初學者提供原始碼的,網址:http://www.mybuffet.cn/html/0/414.htm 你進去可能會挺失望的,因為頁面實在是太醜了,不過好在他提供給我們最實在的原始碼讓我們去學習。上面的那個網址就是一個設定定時器的原始碼連結。不過為了防止該網站以後停掉了,我還是做一個備份。
代碼如下:
using System;<br />using System.Collections.Generic;<br />using System.Text;<br />using System.Threading;</p><p>namespace TimerApp<br />{<br /> class Program<br /> {<br /> static void Main(string[] args)<br /> {<br /> Console.WriteLine("***** Working with Timer type *****/n");</p><p> // Create the delegate for the Timer type.<br /> TimerCallback timeCB = new TimerCallback(PrintTime);</p><p> // Establish timer settings.<br /> Timer t = new Timer(<br /> timeCB, // The TimerCallback delegate type.<br /> "Hello From Main", // Any info to pass into the called method (null for no info).<br /> 0, // Amount of time to wait before starting.<br /> 1000); //一秒鐘調用一次 Interval of time between calls (in milliseconds).</p><p> Console.WriteLine("Hit key to terminate...");<br /> Console.ReadLine();<br /> }</p><p> static void PrintTime(object state)<br /> {<br /> Console.WriteLine("Time is: {0}, Param is: {1}",<br /> DateTime.Now.ToLongTimeString(), state.ToString());<br /> }<br /> }<br />}<br />
你只需要建立一個Console Application項目後,然後把上面的代碼粘貼到類檔案後執行就可以了,具體的大家自己去發揮自己的創新能力了。