Reputation: 24552
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();
}
}
}
Upvotes: 5
Views: 322
Reputation: 104
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.
Upvotes: 2