C# Timer 計時器 TimerCallback

來源:互聯網
上載者:User

看到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項目後,然後把上面的代碼粘貼到類檔案後執行就可以了,具體的大家自己去發揮自己的創新能力了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.