例說定時器System.Threading.Timer

來源:互聯網
上載者:User

標籤:

本文通過執行個體示範System.Threading.Timer的使用方法。
下面是完整的執行個體代碼。

using System;using System.Windows;namespace ThreadingTimerExp{    /// <summary>    /// MainWindow.xaml 的互動邏輯    /// </summary>    public partial class MainWindow : Window    {        System.Threading.Timer timer;        int i = 1;        public MainWindow()        {            InitializeComponent();                   }        void timer_Elapsed(object state)        {            this.Dispatcher.BeginInvoke(new Action(() =>            {                this.Label_Text.Content = i++.ToString();            }), null);        }        private void Button_Click_1(object sender, RoutedEventArgs e)        {            timer = new System.Threading.Timer(new System.Threading.TimerCallback(timer_Elapsed), this, 0, 1000);        }    }}

本文執行個體使用下面的建構函式初始化Timer執行個體。
public Timer(TimerCallback callback, object state, int dueTime, int period);
建構函式接收4個參數,這些參數的含義是什麼呢?
callback:一個 TimerCallback 委託,表示要執行的方法。
state:一個包含回調方法要使用的資訊的對象,或者為空白引用。執行個體中將this(表示MainWindow的執行個體)傳入,那麼回調方法中便可以訪問MainWindow的執行個體。
dueTime:調用 callback 之前延遲的時間量(以毫秒為單位)。指定 Timeout.Infinite 以防止計時器開始計時。指定零 (0) 以立即啟動計時器。
period:調用 callback 的時間間隔(以毫秒為單位)。指定 Timeout.Infinite 可以禁用定期終止。
Timer建構函式還有以下幾種重載形式。

public Timer(TimerCallback callback);public Timer(TimerCallback callback, object state, long dueTime, long period);public Timer(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period);public Timer(TimerCallback callback, object state, uint dueTime, uint period);

System.Threading.Timer是多線程定時器,所以更新UI畫面同樣需要藉助於this.Dispatcher.BeginInvoke()方法。
System.Threading.Timer與System.Timers.Timer類似,System.Timers.Timer是對System.Threading.Timer的簡單封裝,所以一般使用System.Timers.Timer會更加方便。

例說定時器System.Threading.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.