C#/XAML App suspend: Bug/Feature – OnNavigatedFrom called during app Suspend

Got hit by this bug in suspension manager (C# and XAML) and wanted to share it with you in case you ever hit this scenario.

Recently, I have been coding an app with Azure backing and I got hit by a bunch of interesting scenarios that left me scratching my head, thinking, “Hmm, how do I do that again?” The following is one of those scenarios.

I was testing my app in the Suspend and Resume Scenarios. If you don’t know, Visual Studio has a very convenient way to Suspend and Resume apps while under the debugger (View->ToolBars->Debug Location) which are available when the app is running under the debugger. Anyway, during the testing of my app, I realized that although I was taking appropriate actions, my app when resumed from a suspend was not working properly. Here is the scenario in detail:

In my app, I have a page, which, when entering up in OnNavigatedTo registers a few event handlers, starts timers etc. When I am exiting this page, I want to clear  up all the event handlers/timers etc. so nothing untowards happens later if the user has navigated away from the page while the timers were still running or if an event handler gets fired later from a callback. The problem I hit was that in App Suspend, the suspension manager calls the OnNavigatedFrom event handler of the page where all my unregister logic was present. This caused a severe problem because when the user would come back to the page after suspend, all the event handlers etc would be unregistered. So the problem is that during suspend, OnNavigatedFrom is called but during Resume OnNavigatedTo is not called.

Anyways, to cut long story short, after searching a lot, I found that this issue has been asked on MSDN, is acknowledged by the product team as a known issue and considered “By Design.” The way I got around was by following the suggestion in the above link which is to say put all of your unregister code in “OnNavigatingFrom” instead of “OnNavigatedFrom”. OnNavigatingFrom is NOT called by the suspension code and is called only when you really are navigating away from the page, so that resolved my issue.

Hope it saves you a bit of time and head scratching.

Leave a comment

Your email address will not be published. Required fields are marked *