App Lifecycle
Understanding the application lifecycle is fundamental to building robust and responsive Universal Windows Platform (UWP) applications. The UWP app lifecycle manages the state of your application, allowing it to suspend, resume, and terminate gracefully.
Core Concepts
A UWP application has several distinct states: running, suspended, and terminated.
Running State
When a user launches your application, it enters the running state. In this state, the application is actively executing code and is visible to the user. The system monitors resource usage, and if an application has been running for too long without user interaction, or if system resources are needed for other applications, it may be suspended.
Suspended State
When the user navigates away from your application (e.g., switches to another app or goes to the Start screen), the UWP framework suspends the application. In the suspended state, your application's process is kept alive in memory, but its execution is paused. This allows for a quick resume when the user returns to the app. During suspension, the system may reclaim resources, so it's crucial to save application state.
Terminated State
If the system needs to reclaim memory or if the application has been suspended for an extended period, it may be terminated. When a terminated application is launched again, it must be restarted from scratch. The UWP framework provides mechanisms to restore the application to its previous state if state was properly saved.
Lifecycle Events
Your application needs to handle specific events to respond to these state changes. The primary event handlers are defined in your app's main class (typically App.xaml.cs).
OnLaunched
This event is fired when the application is first launched or resumed from a terminated state. You should use this method to initialize your application, create the main window, and restore the application's state if necessary.
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
// Initialize UI, load data, restore state
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
rootFrame = new Frame();
Window.Current.Content = rootFrame;
}
if (e.PrelaunchActivated == false)
{
if (rootFrame.Content == null)
{
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
Window.Current.Activate();
}
}
OnSuspending
This event is fired when the application is about to be suspended. It's critical to save any unsaved application data or user state here to ensure a smooth resume experience.
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
// Save application state and data
// Example: Save user preferences, current page, etc.
deferral.Complete();
}
OnNavigationFailed
Handles navigation failures within the application's frame.
void Frame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception($"Failed to load Page {e.SourcePageType.FullName}: {e.Exception}");
}
State Management
Effective state management is key to a good user experience in UWP. You should leverage the suspension and resume points to:
- Save unsaved user input.
- Store the current navigation state.
- Persist application settings.
- Release resources that are not needed in the suspended state.
Common methods for state management include:
ApplicationData.Current.LocalSettingsfor simple settings.ApplicationData.Current.RoamingSettingsfor settings that sync across devices.- Serialization of data objects to files.
Resuming an Application
When an application resumes from a suspended state, the `OnLaunched` method is called again. You can check the `LaunchActivatedEventArgs.PreviousExecutionState` to determine if the app was previously suspended and then restore its state accordingly.
| Method/Event | Description |
|---|---|
OnLaunched |
Called when the app is launched or resumed from termination. |
OnActivated |
Called when the app is activated by a specific contract (e.g., file picker). |
OnSuspending |
Called just before the app is suspended. Save state here. |
OnResuming |
Called when the app is resumed from suspension. |
Best Practices
- Always save critical data when
OnSuspendingis called. - Avoid long-running operations in
OnSuspendingas it has a limited time window. - Use
deferral.Complete()inOnSuspendingto signal that saving is done. - Handle the
OnResumingevent for any specific actions needed upon resuming that aren't covered byOnLaunchedstate restoration. - Keep your application responsive by performing heavy work on background threads.