C# 多線程的自動管理(定時器)

來源:互聯網
上載者:User

Timer 類:
    設定一個定時器,定時執行使用者指定的函數。定時器啟動後,系統將自動建立一個新的線程,執行使用者指定的函數。

using System;

using System.Threading;

namespace ThreadExample

{

    class TimerExampleState

    {

        public int counter = 0;

        public Timer tmr;

    }

 

    class App

    {

        public static void Main()

        {

            TimerExampleState s = new TimerExampleState();

 

            // 建立代理對象 System.Threading.TimerCallback,該代理將被定時調用 

            TimerCallback timerDelegate = new TimerCallback(CheckStatus);

            

            // 建立一個時間間隔為 1s 的定時器 

            // 第1個參數:指定了 TimerCallback 委託,表示要執行的方法; 

            // 第2個參數:一個包含回調方法要使用的資訊的對象,或者為空白引用; 

            // 第3個參數:延遲時間--計時開始的時刻距現在的時間,單位是毫秒,指定為"0"表示 立即啟動計時器; 

            // 第4個參數:定時器的時間間隔--計時開始後,每隔這麼長的一段時間,TimerCallback 所代表的方法將被調用一次 

            Timer timer = new Timer(timerDelegate, s, 1000, 1000);

            s.tmr = timer;

            

            // 主線程停下來等待 Timer 對象的終止 

            while (s.tmr != null)

            {

                Thread.Sleep(0);

            }

            Console.WriteLine("Timer example done.");

            Console.ReadLine();

        }

 

        /// <summary>

        /// 下面是被定時調用的方法

        /// </summary>

        /// <param name="state"></param> 

        static void CheckStatus(Object state)

        {

            TimerExampleState s = (TimerExampleState)state;

            s.counter++;

            Console.WriteLine("{0} Checking Status {1}.", DateTime.Now.TimeOfDay, s.counter);

            if (s.counter == 5)

            {

                //使用 Change 方法改變了時間間隔為2秒,再等待10秒 

                (s.tmr).Change(10000, 2000);

                Console.WriteLine("changed");                

            }

            if (s.counter == 10)

            {

                Console.WriteLine("disposing of timer!");

                s.tmr.Dispose();

                s.tmr = null;

            }

        }

    }

}

     程式首先建立了一個定時器,它將在建立 1 秒之後開始每隔 1 秒調用一次 CheckStatus() 方法。當調用 5 次以後,CheckStatus() 方法中修改了時間間隔為 2 秒,在並且指定在 10 秒後重新開始。當計數達到 10 次, 調用 Timer.Dispose()方法刪除了 timer 對象,主線程於是跳出迴圈,終止程式。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.