3

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.

Jerry Nixon
  • 31,313
  • 14
  • 117
  • 233

1 Answers1

2

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.

Jerry Nixon
  • 31,313
  • 14
  • 117
  • 233
  • Suspending != closing – lindexi Nov 02 '16 at 03:18
  • @lindexi - I think the first sentence addresses that. For a developer, the difference is rather thin with UWP. – H H Nov 02 '16 at 15:52
  • @lindexi even though you are right, you can be wrong, too. When your application is suspended, the Suspending event is raised. When your application is closed, the Suspending event is raised. There is no reliable way to differentiate. As a result, you must treat Suspending like Closing. – Jerry Nixon Dec 09 '16 at 16:42