ELDONXP
ELDONXP

Reputation: 11

Change messageTimer.Interval at runtime even if the messageTimer is in another method

I want to change the interval of my dispatcher time in run time here is my code :

InitializeComponent();
        DispatcherTimer messageTimer = new DispatcherTimer();
        messageTimer.Tick += new EventHandler(messageTimer_Tick);
        messageTimer.Interval =  TimeSpan.FromSeconds(1);
        messageTimer.Start();

idk how to change the interval of the DispatcherTimer at run time

Upvotes: 0

Views: 68

Answers (1)

takim
takim

Reputation: 81

I created two textblocks and a button.

  1. textblock : x:Name="txt_Count"

  2. textblock : x:Name="txt_TimeNow"

  3. Button : x:Name="btn_changeTime_s"

         int count = 0;
         DispatcherTimer messageTimer;
         DispatcherTimer TimeNow;
         public MainWindow()
         {
             InitializeComponent();
    
             messageTimer = new DispatcherTimer();
             messageTimer.Tick += new EventHandler(messageTimer_Tick);
             messageTimer.Interval = TimeSpan.FromSeconds(1);
             messageTimer.Start();
    
             TimeNow = new DispatcherTimer();
             TimeNow.Tick += new EventHandler(TimeNow_Tick);
             TimeNow.Interval = TimeSpan.FromMilliseconds(100);
             TimeNow.Start();
         }
    
         private void TimeNow_Tick(object sender, EventArgs e)
         {
             txt_now.Text = DateTime.Now.ToString();
         }
    
         private void messageTimer_Tick(object sender, EventArgs e)
         {
             txt_Count.Text = count.ToString();
             count++;
         }
    
         private void btn_changeTime_s_Click(object sender, RoutedEventArgs e)
         {
             messageTimer.Interval = TimeSpan.FromSeconds(2);
         }
    

If you need to modify the Main UI Thread in the background, use the syntax

 txt_Count.Dispatcher.Invoke(DispatcherPriority.Normal,new Action(delegate ()
              {
                  txt_Count.Text = count.ToString();
              }
              ));

Upvotes: 0

Related Questions