當前位置:開發者網絡 >> 技術教程 >> .NET教程 >> 算法/線程 >> 內容
精彩推薦
分類最新教程
分類熱點教程
    
結合singleton和線程做一個定時服務(給藍)
作者:未知
日期:2003-07-12
人氣:
投稿:Andy.m(轉貼)
來源:未知
字體:
收藏:加入瀏覽器收藏
以下正文:
   design pattern的singleton是一個雖然簡單但很有用處的模式,它的作用就是使類只能有一個實例,不需要實例化,而提供一個唯一的全局切入點。如果再結合上線程,完全可以實現一個定時服務,不像Timer控件,它不僅可以應用在windows應用程序中,同樣可以應用於web程序中,就像剛才藍說的那種效果。看下面這個簡單的例子吧。

using System;
using System.Threading ;

namespace testall
{
    /// <summary>
    /// 一個web job的示例類
    /// </summary>
    /// <remarks>符合design pattern的singleton模式</remarks>
    public class TestStatic
    {
        /// <summary>
        /// 定時間隔
        /// </summary>
        /// <remarks>通過修改這個常量決定間隔多長時間做某件事</remarks>
        const int DELAY_TIMES = 1000 ;

        /// <summary>
        /// 一個計數器
        /// </summary>
        private int m_intCounter = 0;

        /// <summary>
        /// 是否退出
        /// </summary>
        private bool m_bCanExit = false ;

        /// <summary>
        /// 線程
        /// </summary>
        private Thread thread ;

        /// <summary>
        /// 自身實例
        /// </summary>
        /// <remarks>注意,這是實現singleton的關鍵</remarks>
        private  static TestStatic instance = new TestStatic() ;

        public int Counter
        {
            get
            {
                return this.m_intCounter ;
            }
            set
            {
                this.m_intCounter = value ;
            }
        }

        public bool CanExit
        {
            set
            {
                this.m_bCanExit = value ;
            }
        }

        /// <summary>
        /// 構造函數
        /// </summary>
        public TestStatic()
        {
            //
            // TODO: Add constructor logic here
            //
            this.m_intCounter = 0 ;
            Console.WriteLine("constructor is running") ;
            this.thread = new Thread(new ThreadStart(ThreadProc)) ;
            thread.Name = "online user" ;
            thread.Start() ;
            Console.WriteLine("完畢") ;
        }


        /// <summary>
        /// 實現singleton的關鍵
        /// </summary>
        /// <returns>類本身的一個實例</returns>
        /// <remarks>唯一的全局切入點</remarks>
        public static TestStatic GetInstance()
        {
            return instance ;
        }

        /// <summary>
        /// 線程工作函數
        /// </summary>
        /// <remarks>想做什麼寫在這兒</remarks>
        private void ThreadProc()
        {
            while(!this.m_bCanExit)
            {
                this.m_intCounter ++ ;
                Console.WriteLine(this.m_intCounter.ToString()) ;
                Thread.Sleep(DELAY_TIMES) ;
            }
        }

        static void Main(string[] args)
        {
            //
            // TODO: Add code to start application here
            //
            Console.WriteLine(TestStatic.GetInstance().Counter.ToString()) ;
            Console.Read() ;
            TestStatic.GetInstance().CanExit = true ;
        }

    }

}
相關文章: