处理应用暂停Handle app suspend

重要的 APIImportant APIs

了解当系统挂起你的应用时如何保存重要的应用程序数据。Learn how to save important application data when the system suspends your app. 以下示例向事件处理程序注册 Suspending 事件并将字符串保存到文件中。The example registers an event handler for the Suspending event and saves a string to a file.

注册暂停的事件处理程序Register the suspending event handler

注册以处理 Suspending 事件,该事件指示在系统暂停你的应用之前,应用应该保存其应用程序数据。Register to handle the Suspending event, which indicates that your app should save its application data before the system suspends it.

using System;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;

partial class MainPage
{
   public MainPage()
   {
      InitializeComponent();
      Application.Current.Suspending += new SuspendingEventHandler(App_Suspending);
   }
}
Public NotInheritable Class MainPage

   Public Sub New()
      InitializeComponent()
      AddHandler Application.Current.Suspending, AddressOf App_Suspending
   End Sub
   
End Class
MainPage::MainPage()
{
    InitializeComponent();
    Windows::UI::Xaml::Application::Current().Suspending({ this, &MainPage::App_Suspending });
}
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::Foundation;
using namespace Windows::UI::Xaml;
using namespace AppName;

MainPage::MainPage()
{
   InitializeComponent();
   Application::Current->Suspending +=
       ref new SuspendingEventHandler(this, &MainPage::App_Suspending);
}

在挂起之前保存应用程序数据Save application data before suspension

当你的应用处理 Suspending 事件时,它将有机会将其重要的应用程序数据保存到处理程序函数中。When your app handles the Suspending event, it has the opportunity to save its important application data in the handler function. 应用应该使用 LocalSettings 存储 API 来同步保存简单的应用程序数据。The app should use the LocalSettings storage API to save simple application data synchronously.

partial class MainPage
{
    async void App_Suspending(
        Object sender,
        Windows.ApplicationModel.SuspendingEventArgs e)
    {
        // TODO: This is the time to save app data in case the process is terminated.
    }
}
Public NonInheritable Class MainPage

    Private Sub App_Suspending(
        sender As Object,
        e As Windows.ApplicationModel.SuspendingEventArgs) Handles OnSuspendEvent.Suspending

        ' TODO: This is the time to save app data in case the process is terminated.
    End Sub

End Class
void MainPage::App_Suspending(
    Windows::Foundation::IInspectable const& /* sender */,
    Windows::ApplicationModel::SuspendingEventArgs const& /* e */)
{
    // TODO: This is the time to save app data in case the process is terminated.
}
void MainPage::App_Suspending(Object^ sender, SuspendingEventArgs^ e)
{
    // TODO: This is the time to save app data in case the process is terminated.
}

释放资源Release resources

你应释放独占资源和文件句柄,以便其他应用可以在你的应用暂停时访问它们。You should release exclusive resources and file handles so that other apps can access them while your app is suspended. 独占资源的示例包括相机、I/O 设备、外部设备以及网络资源。Examples of exclusive resources include cameras, I/O devices, external devices, and network resources. 显式释放独占资源和文件句柄有助于确保其他应用可以在你的应用暂停时访问它们。Explicitly releasing exclusive resources and file handles helps to ensure that other apps can access them while your app is suspended. 当恢复应用时,它应该重新获取其独占资源和文件句柄。When the app is resumed, it should reacquire its exclusive resources and file handles.

备注Remarks

每当用户切换到其他应用、桌面或“开始”屏幕时,系统都会暂停你的应用。The system suspends your app whenever the user switches to another app or to the desktop or Start screen. 每当用户切回到你的应用时,系统就会恢复你的应用。The system resumes your app whenever the user switches back to it. 当系统恢复你的应用时,你的变量和数据结构的内容与系统将你的应用暂停之前的内容相同。When the system resumes your app, the content of your variables and data structures is the same as it was before the system suspended the app. 系统会将你的应用完全恢复到你离开时的状态,使用户感觉你的应用好像一直在后台运行一样。The system restores the app exactly where it left off, so that it appears to the user as if it's been running in the background.

当你的应用暂停时,系统会尝试将你的应用及其数据保留在内存中。The system attempts to keep your app and its data in memory while it's suspended. 但是,如果系统没有资源将你的应用保存在内存里,则将终止你的应用。However, if the system does not have the resources to keep your app in memory, the system will terminate your app. 当用户切换回已终止的暂停应用时,该应用会发送 Activated 事件,且应该在其 OnLaunched 方法中还原其应用程序数据。When the user switches back to a suspended app that has been terminated, the system sends an Activated event and should restore its application data in its OnLaunched method.

当终止应用时系统不会通知应用,因此当暂停应用时,你的应用必须保存其应用程序数据并释放独占资源和文件句柄,并且在终止后又激活应用时还原这些内容。The system doesn't notify an app when it's terminated, so your app must save its application data and release exclusive resources and file handles when it's suspended, and restore them when the app is activated after termination.

如果在处理程序中执行异步调用,控件将立即从该异步调用中返回。If you make an asynchronous call within your handler, control returns immediately from that asynchronous call. 这意味着,执行之后会从事件处理程序中返回,并且应用会转变为下一个状态,即使异步调用尚未完成。That means that execution can then return from your event handler and your app will move to the next state even though the asynchronous call hasn't completed yet. 使用传递给事件处理程序的 EnteredBackgroundEventArgs 对象上的 GetDeferral 方法以延迟暂停,直到调用返回的 Windows.Foundation.Deferral 对象上的 Complete 方法。Use the GetDeferral method on the EnteredBackgroundEventArgs object that is passed to your event handler to delay suspension until after you call the Complete method on the returned Windows.Foundation.Deferral object.

延迟并不会增加应用终止之前需要运行的代码量。A deferral doesn't increase the amount you have to run your code before your app is terminated. 它只延迟终止,直到调用延迟的 Complete 方法,或者达到截止时间,以先发生者为准It only delays termination until either the deferral's Complete method is called, or the deadline passes-whichever comes first. 要延长处于“暂停中”状态的事件,请使用 ExtendedExecutionSessionTo extend time in the Suspending state use ExtendedExecutionSession

备注

若要提高 Windows 8.1 中的系统响应能力,在挂起应用程序后,将对其授予低优先级访问资源的权限。To improve system responsiveness in Windows 8.1, apps are given low priority access to resources after they are suspended. 为了支持新的优先级,延长了暂停操作超时,以便应用具有与普通优先级相当的 5 秒(在 Windows 上)或者 1 到 10 秒超时(在 Windows Phone 上)。To support this new priority, the suspend operation timeout is extended so that the app has the equivalent of the 5-second timeout for normal priority on Windows or between 1 and 10 seconds on Windows Phone. 你无法扩展或改变此超时窗口。You cannot extend or alter this timeout window.

有关使用 Visual Studio 进行调试的说明: Visual Studio 阻止 Windows 挂起附加到调试器的应用程序。A note about debugging using Visual Studio: Visual Studio prevents Windows from suspending an app that is attached to the debugger. 这是为了允许用户在应用正在运行时查看 Visual Studio 调试 UI。This is to allow the user to view the Visual Studio debug UI while the app is running. 调试应用时,可以使用 Visual Studio 将一个暂停事件发送给该应用。When you're debugging an app, you can send it a suspend event using Visual Studio. 请确保正在显示 " 调试位置 " 工具栏,然后单击 " 挂起 " 图标。Make sure the Debug Location toolbar is being shown, then click the Suspend icon.