Friday, August 18, 2017

How can I correctly run a timed process in my app the will start on stop when the application is in use or in the background?

Leave a Comment

I have an application that starts up and runs a background check of the database every minute. Below is the code for this.

I'm getting what I think is a memory leak and am looking at all areas of the code that loop.

Is there any possibility that this code could be left in a looping state and contribute to a memory leak or is the way the onSleep and onResume coded a 100% sure way to correctly stop and start the timer loop?

Note that I only want the timed part of the code to run once a minute when the application is being used and in the foreground.

namespace Japanese {     public partial class App : Application     {          private static Stopwatch stopWatch = new Stopwatch();          public App()         {             InitializeComponent();             MainPage = new Japanese.MainPage();         }          protected override void OnStart()         {             App.DB.InitData();              if (!stopWatch.IsRunning)                  stopWatch.Start();              Device.StartTimer(new TimeSpan(0, 0, 1), () =>             {                 if (stopWatch.IsRunning && stopWatch.Elapsed.Minutes >= defaultTimespan)                 {                     Debug.WriteLine("Checking database");                     PointChecker.CheckScore();                     stopWatch.Restart();                 }                 return true;             });         }          protected override void OnSleep()         {             stopWatch.Reset();         }          protected override void OnResume()         {             stopWatch.Start();         }      } } 

1 Answers

Answers 1

The App class is the class that represents the cross-platform mobile application, it is running even your "MainPage" was not, so i think you need to use OnAppearing and OnDisappearing methods in your main page (a :ContentPage).

Maybe something like :

protected override void OnAppearing() {    stopWatch.Start();    base.OnAppearing(); } 

and,

protected override void OnDisappearing() {  stopWatch.Reset();  base.OnDisappearing(); } 

I hope that helps, Mabrouk.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment