How can I correctly start the synchronized process in my application, will it start by stopping when the application will be used or in the background?

I have an application that launches and runs a database check every minute. Below is the code for this.

I get what, in my opinion, is a memory leak, and I look at all areas of the code that loop.

Is it likely that this code can be left in a loop state and contribute to a memory leak, or the way that onSleep and onResume encode a 100% way to stop and start the timer cycle correctly?

Please note that I want the time taken to execute the code to be executed once a minute, when the application is 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(); } } } 
+6
xamarin xamarin.forms
source share
1 answer

The App class is a class representing a cross-platform mobile application, it even works on your "MainPage", so I believe that you need to use the OnAppearing and OnDisappearing on the main page ( :ContentPage ).

Maybe something like:

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

and

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

I hope this helps, Mabrouk.

+2
source share

All Articles