question

6666666 avatar image
0 Votes"
6666666 asked KyleWang-MSFT edited

How to keep only one timer in the page?

I want to create a timer when user open the page and close it when leave the page.

I know I can use Device.StartTimer to do it.

but If I open and close it very quickly it may open two or more timers.
one not closed then open another.

If I add a flag IsWorking then it will create more too.

how to do it?

dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

KyleWang-MSFT avatar image
0 Votes"
KyleWang-MSFT answered KyleWang-MSFT edited

Hi 6666666,

Welcome to our Microsoft Q&A platform!

I defined a boolean field to check if the "timer page" is closed. And override the "OnAppearing()" and "OnDisappearing()" of the "timer page". In my test, everything works fine. Only one timer is running at a time, and when the "timer page" is closed, the previous timer will also be stopped.

Here is the simple demo.

 bool timer_on = true;
 int count = 0;
    
 protected override void OnAppearing()
 {
     base.OnAppearing();
     Device.StartTimer(TimeSpan.FromMilliseconds(100), () =>
     {
         if (timer_on)
         {
             Console.WriteLine(++count);
             return true;
         }
    
         return false;
     });
 }
    
 protected override void OnDisappearing()
 {
     base.OnDisappearing();
     timer_on = false;
 }

Regards,
Kyle


If the response is helpful, please click "Accept Answer" and upvote it.

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.

· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

If TimeSpan.FromMilliseonds(10000); I open the page then close then re-open.

there will be 2 timer right?

0 Votes 0 ·

@6666666 Tested "TimeSpan.FromMilliseconds(10000)" and it also works fine. By adding a breakpoint at "return false;" line, we can find that when the user exits the page and the timer executes to the next turn, "return false;" will be executed to terminate the timer.

0 Votes 0 ·

yes If you return true. and then exit the page you want to say it will return false right? but if I open the page then the timer is not exit. it will return true again.

then there will be two timer which will return true.

0 Votes 0 ·
Show more comments