Search code examples
uwptemplate10

How do I handle when a UWP application is closing?


Sometimes I have an open stream or an active queue that has to be properly handled when the application is closing. In WPF applications, I could use the Unloading event on the application, but in UWP I notice that such an event does not exist.

How do I do this reliably?

PS: I am using the Template 10 framework.


Solution

  • In a generic UWP application the only reliable way to know that your application is closing is to attach to the Suspending event in the application class. To do this effectively, you need to handle the event and message this operation somehow into your view-model where you can close your stream or clear your queue.

    public App()
    {
        this.InitializeComponent();
        this.Suspending += App_Suspending;
    }
    
    private void App_Suspending(Object sender, SuspendingEventArgs e)
    {
        // close stream
    }
    

    In a Template 10 application the best way to do this is to override the OnNavigatedFrom method in your view-model and look if the suspending argument is true. If it is, then your application is closing and it is the appropriate time to close your stream or clear your queue. Don't mess with the application class.

    public override Task OnNavigatedFromAsync(IDictionary<String, Object> pageState, Boolean suspending)
    {
        if (suspending)
        {
            // close stream
        }
        return base.OnNavigatedFromAsync(pageState, suspending);
    }
    

    Alternatively, if you are using Template 10 without view-models, which is 100% supported, the Template 10 application class provides an override instead of an event to handle. Override this method and close your stream there.

    public override Task OnSuspendingAsync(Object s, SuspendingEventArgs e, Boolean prelaunchActivated)
    {
        // close stream
        return base.OnSuspendingAsync(s, e, prelaunchActivated);
    }
    

    Best of luck.