Muokkaa

Jaa


Free memory when your app moves to the background

This article shows you how to reduce the amount of memory that your app uses when it moves to the background state so that it won't be suspended and possibly terminated.

New background events

Windows 10, version 1607, introduces two new application lifecycle events, EnteredBackground and LeavingBackground. These events let your app know when it is entering and leaving the background.

When your app moves into the background, the memory constraints enforced by the system may change. Use these events to check your current memory consumption and free resources in order to stay below the limit so that your app won't be suspended and possibly terminated while it is in the background.

Events for controlling your app's memory usage

MemoryManager.AppMemoryUsageLimitChanging is raised just before the limit of total memory the app can use is changed. For example, when the app moves into the background and on the Xbox the memory limit changes from 1024MB to 128MB.
This is the most important event to handle to keep the platform from suspending or terminating the app.

MemoryManager.AppMemoryUsageIncreased is raised when the app's memory consumption has increased to a higher value in the AppMemoryUsageLevel enumeration. For example, from Low to Medium. Handling this event is optional but recommended because the application is still responsible for staying under the limit.

MemoryManager.AppMemoryUsageDecreased is raised when the app's memory consumption has decreased to a lower value in the AppMemoryUsageLevel enumeration. For example, from High to Low. Handling this event is optional but indicates the application may be able to allocate additional memory if needed.

Handle the transition between foreground and background

When your app moves from the foreground to the background, the EnteredBackground event is raised. When your app returns to the foreground, the LeavingBackground event is raised. You can register handlers for these events when your app is created. In the default project template, this is done in the App class constructor in App.xaml.cs.

Because running in the background will reduce the memory resources your app is allowed to retain, you should also register for the AppMemoryUsageIncreased and AppMemoryUsageLimitChanging events which you can use to check your app's current memory usage and the current limit. The handlers for these events are shown in the following examples. For more information on the application lifecycle for UWP apps, see App lifecycle.

public App()
{
    this.InitializeComponent();

    this.Suspending += OnSuspending;

    // Subscribe to key lifecyle events to know when the app
    // transitions to and from foreground and background.
    // Leaving the background is an important transition
    // because the app may need to restore UI.
    this.EnteredBackground += AppEnteredBackground;
    this.LeavingBackground += AppLeavingBackground;

    // During the transition from foreground to background the
    // memory limit allowed for the application changes. The application
    // has a short time to respond by bringing its memory usage
    // under the new limit.
    Windows.System.MemoryManager.AppMemoryUsageLimitChanging += MemoryManager_AppMemoryUsageLimitChanging;

    // After an application is backgrounded it is expected to stay
    // under a memory target to maintain priority to keep running.
    // Subscribe to the event that informs the app of this change.
    Windows.System.MemoryManager.AppMemoryUsageIncreased += MemoryManager_AppMemoryUsageIncreased;
}

When the EnteredBackground event is raised, set the tracking variable to indicate that you are currently running in the background. This will be useful when you write the code for reducing memory usage.

/// <summary>
/// The application entered the background.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AppEnteredBackground(object sender, EnteredBackgroundEventArgs e)
{
    _isInBackgroundMode = true;

    // An application may wish to release views and view data
    // here since the UI is no longer visible.
    //
    // As a performance optimization, here we note instead that
    // the app has entered background mode with _isInBackgroundMode and
    // defer unloading views until AppMemoryUsageLimitChanging or
    // AppMemoryUsageIncreased is raised with an indication that
    // the application is under memory pressure.
}

When your app transitions to the background, the system reduces the memory limit for the app to ensure that the current foreground app has sufficient resources to provide a responsive user experience

The AppMemoryUsageLimitChanging event handler lets your app know that its allotted memory has been reduced and provides the new limit in the event arguments passed into the handler. Compare the MemoryManager.AppMemoryUsage property, which provides your app's current usage, to the NewLimit property of the event arguments, which specifies the new limit. If your memory usage exceeds the limit, you need to reduce your memory usage.

In this example, this is done in the helper method ReduceMemoryUsage, which is defined later in this article.

/// <summary>
/// Raised when the memory limit for the app is changing, such as when the app
/// enters the background.
/// </summary>
/// <remarks>
/// If the app is using more than the new limit, it must reduce memory within 2 seconds
/// on some platforms in order to avoid being suspended or terminated.
///
/// While some platforms will allow the application
/// to continue running over the limit, reducing usage in the time
/// allotted will enable the best experience across the broadest range of devices.
/// </remarks>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MemoryManager_AppMemoryUsageLimitChanging(object sender, AppMemoryUsageLimitChangingEventArgs e)
{
    // If app memory usage is over the limit, reduce usage within 2 seconds
    // so that the system does not suspend the app
    if (MemoryManager.AppMemoryUsage >= e.NewLimit)
    {
        ReduceMemoryUsage(e.NewLimit);
    }
}

Note

Some device configurations will allow an application to continue running over the new memory limit until the system experiences resource pressure, and some will not. On Xbox, in particular, apps will be suspended or terminated if they do not reduce memory to under the new limits within 2 seconds. This means that you can deliver the best experience across the broadest range of devices by using this event to reduce resource usage below the limit within 2 seconds of the event being raised.

It is possible that although your app's memory usage is currently under the memory limit for background apps when it first transitions to the background, it may increase its memory consumption over time and begin to approach the limit. The handler the AppMemoryUsageIncreased provides an opportunity to check your current usage when it increases and, if necessary, free memory.

Check to see if the AppMemoryUsageLevel is High or OverLimit, and if so, reduce your memory usage. In this example this is handled by the helper method, ReduceMemoryUsage. You can also subscribe to the AppMemoryUsageDecreased event, check to see if your app is under the limit, and if so then you know you can allocate additional resources.

/// <summary>
/// Handle system notifications that the app has increased its
/// memory usage level compared to its current target.
/// </summary>
/// <remarks>
/// The app may have increased its usage or the app may have moved
/// to the background and the system lowered the target for the app
/// In either case, if the application wants to maintain its priority
/// to avoid being suspended before other apps, it may need to reduce
/// its memory usage.
///
/// This is not a replacement for handling AppMemoryUsageLimitChanging
/// which is critical to ensure the app immediately gets below the new
/// limit. However, once the app is allowed to continue running and
/// policy is applied, some apps may wish to continue monitoring
/// usage to ensure they remain below the limit.
/// </remarks>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MemoryManager_AppMemoryUsageIncreased(object sender, object e)
{
    // Obtain the current usage level
    var level = MemoryManager.AppMemoryUsageLevel;

    // Check the usage level to determine whether reducing memory is necessary.
    // Memory usage may have been fine when initially entering the background but
    // the app may have increased its memory usage since then and will need to trim back.
    if (level == AppMemoryUsageLevel.OverLimit || level == AppMemoryUsageLevel.High)
    {
        ReduceMemoryUsage(MemoryManager.AppMemoryUsageLimit);
    }
}

ReduceMemoryUsage is a helper method that you can implement to release memory when your app is over the usage limit while running in the background. How you release memory depends on the specifics of your app, but one recommended way to free up memory is to dispose of your UI and the other resources associated with your app view. To do so, ensure that you are running in the background state then set the Content property of your app's window to null and unregister your UI event handlers and remove any other references you may have to the page. Failing to unregister your UI event handlers and clearing any other references you may have to the page will prevent the page resources from being released. Then call GC.Collect to reclaim the freed up memory immediately. Typically you don't force garbage collection because the system will take care of it for you. In this specific case, we are reducing the amount of memory charged to this application as it goes into the background to reduce the likelihood that the system will determine that it should terminate the app to reclaim memory.

/// <summary>
/// Reduces application memory usage.
/// </summary>
/// <remarks>
/// When the app enters the background, receives a memory limit changing
/// event, or receives a memory usage increased event, it can
/// can optionally unload cached data or even its view content in
/// order to reduce memory usage and the chance of being suspended.
///
/// This must be called from multiple event handlers because an application may already
/// be in a high memory usage state when entering the background, or it
/// may be in a low memory usage state with no need to unload resources yet
/// and only enter a higher state later.
/// </remarks>
public void ReduceMemoryUsage(ulong limit)
{
    // If the app has caches or other memory it can free, it should do so now.
    // << App can release memory here >>

    // Additionally, if the application is currently
    // in background mode and still has a view with content
    // then the view can be released to save memory and
    // can be recreated again later when leaving the background.
    if (isInBackgroundMode && Window.Current.Content != null)
    {
        // Some apps may wish to use this helper to explicitly disconnect
        // child references.
        // VisualTreeHelper.DisconnectChildrenRecursive(Window.Current.Content);

        // Clear the view content. Note that views should rely on
        // events like Page.Unloaded to further release resources.
        // Release event handlers in views since references can
        // prevent objects from being collected.
        Window.Current.Content = null;
    }

    // Run the GC to collect released resources.
    GC.Collect();
}

When the window content is collected, each Frame begins its disconnection process. If there are Pages in the visual object tree under the window content, these will begin firing their Unloaded event. Pages cannot be completely cleared from memory unless all references to them are removed. In the Unloaded callback, do the following to ensure that memory is quickly freed:

  • Clear and set any large data structures in your Page to null.
  • Unregister all event handlers that have callback methods within the Page. Make sure to register those callbacks during the Loaded event handler for the Page. The Loaded event is raised when the UI has been reconstituted and the Page has been added to the visual object tree.
  • Call GC.Collect at the end of the Unloaded callback to quickly garbage collect any of the large data structures you have just set to null. Again, typically you don't force garbage collection because the system will take care of it for you. In this specific case, we are reducing the amount of memory charged to this application as it goes into the background to reduce the likelihood that the system will determine that it should terminate the app to reclaim memory.
private void MainPage_Unloaded(object sender, RoutedEventArgs e)
{
   // << free large data sructures and set them to null, here >>

   // Disconnect event handlers for this page so that the garbage
   // collector can free memory associated with the page
   Window.Current.Activated -= Current_Activated;
   GC.Collect();
}

In the LeavingBackground event handler, set the tracking variable (isInBackgroundMode) to indicate that your app is no longer running in the background. Next, check to see if the Content of the current window is null-- which it will be if you disposed of your app views in order to clear up memory while you were running in the background. If the window content is null, rebuild your app view. In this example, the window content is created in the helper method CreateRootFrame.

/// <summary>
/// The application is leaving the background.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AppLeavingBackground(object sender, LeavingBackgroundEventArgs e)
{
    // Mark the transition out of the background state
    _isInBackgroundMode = false;

    // Restore view content if it was previously unloaded
    if (Window.Current.Content == null)
    {
        CreateRootFrame(ApplicationExecutionState.Running, string.Empty);
    }
}

The CreateRootFrame helper method recreates the view content for your app. The code in this method is nearly identical to the OnLaunched handler code provided in the default project template. The one difference is that the Launching handler determines the previous execution state from the PreviousExecutionState property of the LaunchActivatedEventArgs and the CreateRootFrame method simply gets the previous execution state passed in as an argument. To minimize duplicated code, you can refactor the default Launching event handler code to call CreateRootFrame.

void CreateRootFrame(ApplicationExecutionState previousExecutionState, string arguments)
{
    Frame rootFrame = Window.Current.Content as Frame;

    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == null)
    {
        // Create a Frame to act as the navigation context and navigate to the first page
        rootFrame = new Frame();

        // Set the default language
        rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];

        rootFrame.NavigationFailed += OnNavigationFailed;

        if (previousExecutionState == ApplicationExecutionState.Terminated)
        {
            //TODO: Load state from previously suspended application
        }

        // Place the frame in the current Window
        Window.Current.Content = rootFrame;
    }

    if (rootFrame.Content == null)
    {
        // When the navigation stack isn't restored navigate to the first page,
        // configuring the new page by passing required information as a navigation
        // parameter
        rootFrame.Navigate(typeof(MainPage), arguments);
    }
}

Guidelines

Moving from the foreground to the background

When an app moves from the foreground to the background, the system does work on behalf of the app to free up resources that are not needed in the background. For example, the UI frameworks flush cached textures and the video subsystem frees memory allocated on behalf of the app. However, an app will still need to carefully monitor its memory usage to avoid being suspended or terminated by the system.

When an app moves from the foreground to the background it will first get an EnteredBackground event and then a AppMemoryUsageLimitChanging event.

  • Do use the EnteredBackground event to free up UI resources that you know your app does not need while running in the background. For example, you could free the cover art image for a song.
  • Do use the AppMemoryUsageLimitChanging event to ensure that your app is using less memory than the new background limit. Make sure that you free up resources if not. If you do not, your app may be suspended or terminated according to device specific policy.
  • Do manually invoke the garbage collector if your app is over the new memory limit when the AppMemoryUsageLimitChanging event is raised.
  • Do use the AppMemoryUsageIncreased event to continue to monitor your app’s memory usage while running in the background if you expect it to change. If the AppMemoryUsageLevel is High or OverLimit make sure that you free up resources.
  • Consider freeing UI resources in the AppMemoryUsageLimitChanging event handler instead of in the EnteredBackground handler as a performance optimization. Use a boolean value set in the EnteredBackground/LeavingBackground event handlers to track whether the app is in the background or foreground. Then in the AppMemoryUsageLimitChanging event handler, if AppMemoryUsage is over the limit and the app is in the background (based on the Boolean value) you can free UI resources.
  • Do not perform long running operations in the EnteredBackground event because you can cause the transition between applications to appear slow to the user.

Moving from the background to the foreground

When an app moves from the background to the foreground, the app will first get an AppMemoryUsageLimitChanging event and then a LeavingBackground event.

  • Do use the LeavingBackground event to recreate UI resources that your app discarded when moving into the background.
  • Background media playback sample - shows how to free memory when your app moves to the background state.
  • Diagnostic Tools - use the diagnostic tools to observe garbage collection events and validate that your app is releasing memory the way you expect it to.