0

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

ELDONXP
  • 11
  • 2

1 Answers1

0

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();
              }
              ));
takim
  • 81
  • 7
  • i get an error using this : CS0649 The 'cpuram.messageTimer' field is never assigned and will always have its default value of null – ELDONXP Dec 27 '20 at 14:39
  • Try assigning it to a field or assigning null? Like this DispatcherTimer messageTimer = null; OR DispatcherTimer messageTimer = new DispatcherTimer(); – takim Dec 27 '20 at 14:50
  • The would be because, as the message states, you haven't set (assigned) messageTimer to an instance of a dispatchertimer. – Andy Dec 27 '20 at 14:51
  • even after using DispatcherTimer messageTimer = null; i get this error – ELDONXP Dec 27 '20 at 15:05