Replace Dispatcher timer with timer

Dani_S 3,336 Reputation points
2024-04-05T06:32:12.2166667+00:00

Hi,

What is the similar code of dispatcher timer but with timer.

private IDispatcherTimer _timer;

protected override void OnAppearing()

{

  base.OnAppearing();



 MainThread.BeginInvokeOnMainThread(() =>

  {

      SetIndicatorStatus();

      SetTimer();

  });

 if (_timer == null)

  {

     var dispatcher = this.Dispatcher;

      _timer = dispatcher.CreateTimer();

     _timer.Interval = TimeSpan.FromSeconds(30);

      _timer.Tick += (s, e) =>

      {

          MainThread.BeginInvokeOnMainThread(() =>

          {

           SetIndicatorStatus();

             SetTimer();

          });

     };

     _timer.IsRepeating = true;

      _timer.Start();

  }

}

protected override void OnDisappearing()

{

  base.OnDisappearing();

 if (_timer != null)

  {

     _timer.Stop();

  }

}

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,231 questions
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 39,391 Reputation points Microsoft Vendor
    2024-04-05T07:33:25.3533333+00:00

    Hello,

    You can replace DispathTimer with the following code equivalent via Timer.

       private Timer _timer;
    
       protected override void OnAppearing()
        {
    
           base.OnAppearing();
            MainThread.BeginInvokeOnMainThread(() =>
            {
                SetIndicatorStatus();
                SetTimer();
            });
    
    
           if (_timer == null)
            {
                _timer = new System.Threading.Timer(TimerFunction,null,0, 30000);
            }
        }
        private void TimerFunction(Object stateInfo)
        {
            MainThread.BeginInvokeOnMainThread(() =>
            {
                SetIndicatorStatus();
                SetTimer();
            });
        }
        protected override void OnDisappearing()
        {
    
           base.OnDisappearing();
    
           if (_timer != null)
    
           {
    
               _timer.Dispose();
    
           }
        }
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful