joi, 7 octombrie 2010

DispatcherTimer

DispatcherTimer

About

  • A timer that is integrated into the Dispatcher queue which is processed at a specified interval of time and at a specified priority.
  • It raise time notification using Dispatcher class
  • Timers are not guaranteed to execute exactly when the time interval occurs.
  • If a System.Timers.Timer is used in a WPF application, the System.Timers.Timer runs on a different thread then the user interface (UI) thread.
    • In order to access objects on the user interface (UI) thread, it is necessary to post the operation onto the Dispatcher of the user interface (UI) thread using Invoke or BeginInvoke.
  • priority field- used with constructor: you can set it DispatcherPriority.Background priority

Sample



private readonly DispatcherTimer m_dispatcherTimer;

ctor
{
  
     m_dispatcherTimer = new DispatcherTimer(DispatcherPriority.Background, Dispatcher)
                                    {Interval = new TimeSpan(0, 0, 0, 0, 300)};
}

         private void Start()
         {    
             Stop();
             m_dispatcherTimer.Tick += DispatcherTimer_Tick;
             m_dispatcherTimer.Start();
         }

         private void Stop()
         {
            m_dispatcherTimer.Stop();
            m_dispatcherTimer.Tick -= DispatcherTimer_Tick;
        }

        private void DispatcherTimer_Tick(object sender, EventArgs e)
        {
            //do something ...
        }

        private static void IsRunningPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                Start();
            }
            else
            {
                Stop();
            }
        }

        public bool IsRunning
        {
            get { return (bool)GetValue(IsRunningProperty); }
            set { Dispatcher.BeginInvoke(new Action(() => SetValue(IsRunningProperty, value))); }
        }
       public static readonly DependencyProperty IsRunningProperty =
            DependencyProperty.Register("IsRunning", typeof(bool), typeof(ProgressCtrlData), new UIPropertyMetadata(false));



References:
Chris Sells and Ian Griffiths, "Programming WPF", SECOND EDITION, O’Reilly Media


  

Niciun comentariu:

Trimiteți un comentariu