C#自定義基于控制臺(tái)的Timer實(shí)例
本文實(shí)例講述了C#自定義基于控制臺(tái)的Timer實(shí)現(xiàn)方法。分享給大家供大家參考。具體如下:
一、概述
這里實(shí)現(xiàn)了一個(gè)自定義類TimerTest,該類可以模擬一個(gè)Timer,經(jīng)過指定時(shí)間間隔執(zhí)行某個(gè)事件。
二、TimerTest類
//定時(shí)器類 class TimerTest { //線程名 string _ThreadName; public string ThreadName { get { return _ThreadName; } private set { _ThreadName = value; } } //時(shí)間間隔 int _TimeInterval; public int TimeInterval { get { return _TimeInterval; } set { _TimeInterval = value; } } //當(dāng)前計(jì)時(shí)器是否啟用 true:?jiǎn)⒂?false:不啟用 bool _Enabled; public bool Enabled { get { return _Enabled; } set { _Enabled = value; } } //每隔一段時(shí)間需要運(yùn)行的事件 public delegate void TickEventHandler(); public event TickEventHandler TickEvent; /// <summary> /// 建立一個(gè)計(jì)時(shí)器(構(gòu)造函數(shù)) /// </summary> /// <param name="ThreadName">線程名</param> /// <param name="TimeInterval">時(shí)間間隔</param> public TimerTest(string ThreadName, int TimeInterval = int.MaxValue) { this.ThreadName = ThreadName; this.TimeInterval = TimeInterval; this.Enabled = false; } /// <summary> /// 定期執(zhí)行事件 /// </summary> public void Run() { while (true) { //如果當(dāng)前計(jì)時(shí)器并未啟用,則每隔一段時(shí)間檢測(cè)是否被啟用 if (!this.Enabled) { Thread.Sleep(100); continue; } //觸發(fā)事件TickEvent if (TickEvent != null) { TickEvent(); } //休眠一定的時(shí)間,等待下一個(gè)循環(huán) Thread.Sleep(TimeInterval % 100); for (int temp = 0; temp < TimeInterval / 100; temp++) { Thread.Sleep(100); if (!this.Enabled) { break; } } } } }
三、調(diào)用示例
每1000毫秒輸出當(dāng)前的時(shí)間
/// <summary> /// 測(cè)試用事件 /// </summary> static void TestHandler() { //TODO Console.WriteLine(DateTime.Now.ToLongTimeString()); } static void Main(string[] args) { TimerTest tt = new TimerTest("timer_test", 1000); tt.Enabled = true; tt.TickEvent += TestHandler; Thread timer = new Thread(tt.Run); timer.Start(); Console.ReadLine(); }
四、運(yùn)行結(jié)果
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
- C# WinForm-Timer控件的使用
- c# 區(qū)分幾種定時(shí)器(timer)
- C#用timer實(shí)現(xiàn)背單詞小程序
- 詳解C#中的System.Timers.Timer定時(shí)器的使用和定時(shí)自動(dòng)清理內(nèi)存應(yīng)用
- C#中Timer使用及解決重入問題
- [C#].NET中幾種Timer的使用實(shí)例
- C#中自定義高精度Timer定時(shí)器的實(shí)例教程
- 詳解C#中的定時(shí)器Timer類及其垃圾回收機(jī)制
- C#中timer定時(shí)器用法實(shí)例
- C#使用timer實(shí)現(xiàn)的簡(jiǎn)單鬧鐘程序
- C#使用timer定時(shí)在屏幕上輸出信息的方法
- C#中的Timer和DispatcherTimer使用實(shí)例
- C#中Forms.Timer、Timers.Timer、Threading.Timer的用法分析
- c#各種Timer類的區(qū)別與用法介紹
- C#中timer類的用法總結(jié)
- C#中的三種定時(shí)計(jì)時(shí)器Timer用法介紹
相關(guān)文章
C#實(shí)現(xiàn)向函數(shù)傳遞不定參數(shù)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)向函數(shù)傳遞不定參數(shù)的方法,涉及C#操作函數(shù)參數(shù)的相關(guān)技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04C#簡(jiǎn)單的通用基礎(chǔ)字典實(shí)現(xiàn)方法
這篇文章主要介紹了C#簡(jiǎn)單的通用基礎(chǔ)字典實(shí)現(xiàn)方法,包含了字典的索引、記錄、回調(diào)與查詢等技巧,需要的朋友可以參考下2014-12-12C# 編碼好習(xí)慣,獻(xiàn)給所有熱愛c#的同志
c#編寫者,需要培養(yǎng)的一些好習(xí)慣2009-02-02