0

I'm trying to implement a method that is running continually, as long as the app's window is active, if the window is minimized that method should stop.

I'm using an MVVM architecture.

In my code behind I have this method:

    protected override void OnAppearing()
    {
        if (BindingContext is MainPageViewModel vm)
        {
            vm.Init();
        }
    } 

I edited the life cycle events.

public partial class App : Application
{
    public static bool activeWindow;

    public App()
    {
        InitializeComponent();

        MainPage = new AppShell();
    }

    protected override Window CreateWindow(IActivationState activationState)
    {
        Window window = base.CreateWindow(activationState);

        window.Activated += (s, e) => { activeWindow = true; };
        window.Deactivated += (s, e) => { activeWindow = false; };

            return window;
    }

In my view model:

    public async void Init()
    {
        await RunInBackground(TimeSpan.FromSeconds(1));
    }

    async Task RunInBackground(TimeSpan timeSpan)
    {
        var periodicTimer = new PeriodicTimer(timeSpan);
        while (await periodicTimer.WaitForNextTickAsync())
        {
            if (App.activeWindow == true)
            {
                //Run code
            }
            else
                continue;
        }
    }

So, when my page is loaded the method starts and I use the bool variable depending in the life cycle state, activated or deactivated.

Is this good code and efficient? Or is the cancelation token a better way to go?

Thanks in advance.

Joao Lima
  • 87
  • 6
  • 1
    https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/app-lifecycle?view=net-maui-7.0 – Jason Mar 25 '23 at 14:38
  • You will also probably need CancelationToken (https://learn.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads) or something similar to notify your method that you are stoping. If you don't see how to use it I can make a small exemple – Poulpynator Mar 25 '23 at 21:39
  • @Poulpynator, as of now I'm using the above code to stop and restart my method, would it be advantageous to use CancelationToken? – Joao Lima Mar 27 '23 at 08:54
  • 1
    Here are some reason : https://stackoverflow.com/a/30025043/10404482, you don't have to but IMO it's better for clarity (in the sense that's it's the standard) – Poulpynator Mar 27 '23 at 09:06

1 Answers1

1

You can use the Stopped method in the App lifecycle to achieve.

This event is raised when the window is no longer visible. There's no guarantee that an app will resume from this state, because it may be terminated by the operating system.

For use in MVVM architecture, you can refer to the following code:

In the App.cs:

public partial class App : Application
{
      public App()
      {
            InitializeComponent();

            MainPage = new AppShell();
      }
      public static Window Window { get; private set; }
      protected override Window CreateWindow(IActivationState activationState)
      {
            Window window = base.CreateWindow(activationState);
            Window = window;
            return window;
      }
}

In the viewmodel:

     var window = App.Window;
      window.Stopped += (s, e) =>
      {
           Debug.WriteLine("------------>Stopped");
         //your code
      };
Zack
  • 1,255
  • 1
  • 2
  • 5