Windows 10 通用 Windows 平台 (UWP) 应用生命周期Windows 10 universal Windows platform (UWP) app lifecycle

本主题介绍通用 Windows 平台 (UWP) 应用的生命周期,从其激活时直到其关闭。This topic describes the lifecycle of a Universal Windows Platform (UWP) app from the time it is launched until it is closed.

简短历史A little history

在 Windows 8 之前,应用的生命周期非常简单。Before Windows 8, apps had a simple lifecycle. Win32 和 .NET 应用始终处于运行状态或未运行状态。Win32 and .NET apps are either running or not running. 当用户最小化应用或离开应用时,它们将继续运行。When a user minimizes them, or switches away from them, they continue to run. 随着便携设备和电源管理变得日益重要,这种情况不再可行。This was fine until portable devices and power management became increasingly important.

Windows 8 随 UWP 应用引入了新应用程序模型。Windows 8 introduced a new application model with UWP apps. 在高级别上,添加了新的已暂停状态。At a high level, a new suspended state was added. 当用户最小化 UWP 应用或切换到其他应用后,该应用会立刻处于暂停状态。A UWP app is suspended shortly after the user minimizes it or switches to another app. 这意味着应用的线程已停止,并且应用保留在内存中(除非操作系统需要回收资源)。This means that the app's threads are stopped and the app is left in memory unless the operating system needs to reclaim resources. 当用户切换回该应用时,该应用可快速还原到正在运行状态。When the user switches back to the app, it can be quickly restored to a running state.

向需要继续运行的后台应用提供多种方法,如后台任务扩展执行和活动赞助执行(例如,BackgroundMediaEnabled 功能,允许应用继续在后台播放媒体)。There are various ways for apps that need to continue to run when they are in the background such as background tasks, extended execution, and activity sponsored execution (for example, the BackgroundMediaEnabled capability which allows an app to continue to play media in the background). 此外,即使你的应用暂停甚至终止,后台传输操作仍会继续。Also, background transfer operations can continue even if your app is suspended or even terminated. 有关详细信息,请参阅如何下载文件For more info, see How to download a file.

默认情况下,暂停不在前台运行的应用可以节能,同时向当前处于前台的应用提供更多资源。By default, apps that are not in the foreground are suspended which results in power savings and more resources available for the app currently in the foreground.

已暂停状态对作为开发人员的你提出了新要求,因为操作系统可能会选择终止已暂停的应用,以便释放资源。The suspended state adds new requirements for you as a developer because the operating system may elect to terminate a suspended app in order to free up resources. 已终止的应用仍会显示在任务栏中。The terminated app will still appear in the task bar. 当用户单击该应用时,该应用必须恢复它终止之前所处的状态,因为用户不会意识到系统已关闭该应用。When the user click on it, the app must restore the state that it was in before it was terminated because the user will not be aware that the system closed the app. 用户会认为在他们执行其他操作时该应用一直在后台等待,并且希望该应用处于他们离开它之前所处的同一状态。They will think that it has been waiting in the background while they were doing other things and will expect it to be in the same state it was in when they left it. 在本主题中,我们将演示如何实现该目的。In this topic we will look at how to accomplish that.

Windows 10 版本 1607 又引入了两个应用模型状态:在前台运行在后台运行Windows 10, version 1607, introduces two more app model states: Running in foreground and Running in background. 我们还会在接下来的部分中演示这些新状态。We will also look at these new states in the sections that follow.

应用执行状态App execution state

此图显示了从 Windows 10 版本 1607 开始的可能应用模型状态。This illustration represents the possible app model states starting in Windows 10, version 1607. 演练 UWP 应用的典型生命周期。Let's walk through the typical lifecycle of a UWP app.

显示应用执行状态之间转换的状态图

当启动或激活应用时,这些应用会进入在后台运行状态。Apps enter the running in background state when they are launched or activated. 如果应用由于前台应用启动而需要移动到前台,则该应用将获取 LeavingBackground 事件。If the app needs to move into the foreground due to a foreground app launch, the app then gets the LeavingBackground event.

虽然“启动”和“激活”看起来非常相似,但它们在操作系统启动应用时所引用的方法有所不同。Although "launched" and "activated" may seem like similar terms, they refer to different ways the operating system may start your app. 首先查看如何启动应用。Let's first look at launching an app.

应用启动App launch

当启动应用时,会调用 OnLaunched 方法。The OnLaunched method is called when an app is launched. 向该方法传递 LaunchActivatedEventArgs 参数,该参数提供的内容包括:已传递给应用的实际参数、启动应用的磁贴的标识符以及应用之前所处的状态。It is passed a LaunchActivatedEventArgs parameter which provides, among other things, the arguments passed to the app, the identifier of the tile that launched the app, and the previous state that the app was in.

LaunchActivatedEventArgs.PreviousExecutionState 获取应用之前的状态,这将返回 ApplicationExecutionStateGet the previous state of your app from LaunchActivatedEventArgs.PreviousExecutionState which returns an ApplicationExecutionState. 其值以及对应状态要采取的操作如下所示:Its values and the appropriate action to take due to that state are as follows:

ApplicationExecutionStateApplicationExecutionState 说明Explanation 采取的操作Action to take
NotRunningNotRunning 应用可能处于此状态,因为该应用自上一次用户重新启动或登录后一直未启动。An app could be in this state because it hasn't been launched since the last time the user rebooted or logged in. 应用在以下情况下也会处于此状态:如果应用运行后出现了故障,或者因为用户之前就将它关闭。It can also be in this state if it was running but then crashed, or because the user closed it earlier. 初始化应用,如同第一次在当前用户会话中运行它。Initialize the app as if it is running for the first time in the current user session.
已挂起Suspended 用户已最小化或离开应用,并且在数秒内未返回该应用。The user either minimized or switched away from your app and didn't return to it within a few seconds. 当应用暂停时,其状态保留在内存中。When the app was suspended, its state remained in memory. 只需重新获取任何文件句柄或应用暂停时释放的其他资源。You only need to reacquire any file handles or other resources you released when the app was suspended.
终止Terminated 应用之前处于暂停状态,但之后某些时候因系统需要回收内存而被终止。The app was previously suspended but was then shutdown at some point because the system needed to reclaim memory. 恢复用户离开应用时应用所处的状态。Restore the state that the app was in when the user switched away from it.
ClosedByUserClosedByUser 用户使用平板电脑模式下的关闭手势或 Alt+F4 关闭了应用。The user closed the app with the close gesture in tablet mode, or with Alt+F4. 当用户关闭应用时,它将首先暂停,然后终止。When the user closes the app, it is first suspended and then terminated. 从本质上说,由于应用经历了导致处于 Terminated 状态的相同步骤,因此处理此状态的步骤与 Terminated 状态相同。Because the app has essentially gone through the same steps that lead to the Terminated state, handle this the same way you would the Terminated state.
正在运行Running 当用户尝试再次启动应用时,该应用已经打开。The app was already open when the user tried to launch it again. 那没有意义。Nothing. 请注意,不会启动应用的另一个实例。Note that another instance of your app is not launched. 只需激活已在运行的实例。The already running instance is simply activated.

注意  当前用户会话基于 Windows 登录。Note  Current user session is based on Windows logon. 只要当前用户未注销、关机或者重新启动 Windows,当前用户会话便可以保留在诸如锁屏界面身份验证、切换用户等的多个事件中。As long as the current user hasn't logged off, shut down, or restarted Windows, the current user session persists across events such as lock screen authentication, switch-user, and so on. 

需要注意的一种重要情形是:如果设备具有足够资源,操作系统会预启动针对该行为选择的常用应用,以优化响应性。One important circumstance to be aware of is that if the device has sufficient resources, the operating system will prelaunch frequently used apps that have opted in for that behavior in order to optimize responsiveness. 在后台启动要预启动的应用,然后快速暂停,以便当用户切换到这些应用时,可以恢复它们,这比启动应用的速度要快得多。Apps that are prelaunched are launched in the background and then quickly suspended so that when the user switches to them, they can be resumed which is faster than launching the app.

由于预启动,可能会由系统(而不是用户)启动应用的 OnLaunched() 方法。Because of prelaunch, the app’s OnLaunched() method may be initiated by the system rather than by the user. 由于应用在后台预启动,因此可能需要在 OnLaunched() 中采取不同操作。Because the app is prelaunched in the background you may need to take different action in OnLaunched(). 例如,当已启动的应用开始播放音乐时,用户不会知道该应用来自何处,因为该应用已在后台预启动。For example, if your app starts playing music when launched, they will not know where it is coming from because the app is prelaunched in the background. 在后台预启动应用后,就会调用 Application.SuspendingOnce your app is prelaunched in the background, it is followed by a call to Application.Suspending. 然后,当用户启动该应用时,将调用 resuming 事件以及 OnLaunched() 方法。Then, when the user does launch the app, the resuming event is invoked as well as the OnLaunched() method. 请参阅处理应用预启动以获取有关如何处理预启动方案的其他信息。See Handle app prelaunch for additional information about how to handle the prelaunch scenario. 仅预启动选择加入的应用。Only apps that opt-in are prelaunched.

当应用启动时,Windows 显示应用的初始屏幕。Windows displays a splash screen for the app when it is launched. 若要配置初始屏幕,请参阅添加初始屏幕To configure the splash screen, see Adding a splash screen.

显示初始屏幕时,应用应该注册事件处理程序以及为初始页面设置它所需的任何自定义 UI。While the splash screen is displayed, your app should register event handlers and set up any custom UI it needs for the initial page. 务必使在应用程序的构造函数和 OnLaunched() 中运行的这些任务在数秒内完成,否则系统可能会认为应用未响应并终止它。See that these tasks running in the application’s constructor and OnLaunched() are completed within a few seconds or the system may think your app is unresponsive and terminate it. 如果某个应用需要从网络请求数据或者需要从磁盘检索大量数据,应完成这些活动,但不启动。If an app needs to request data from the network or needs to retrieve large amounts of data from disk, these activities should be completed outside of launch. 在应用等待这些长时间运行的操作结束的同时,它可以使用自己的自定义加载 UI 或扩展的初始屏幕。An app can use its own custom loading UI or an extended splash screen while it waits for long running operations to finish. 有关详细信息,请参阅延长显示初始屏幕的时间初始屏幕示例See Display a splash screen for more time and the Splash screen sample for more info.

应用完成启动后,它将进入 Running 状态,初始屏幕也将消失,将清除所有初始屏幕资源和对象。After the app completes launching, it enters the Running state and the splash screen disappears and all splash screen resources and objects are cleared.

应用激活App activation

除了由用户启动之外,应用还可以由系统激活。In contrast to being launched by the user, an app can be activated by the system. 应用可以由合约(如“共享”合约)激活。An app may be activated by a contract such as the share contract. 或者应用可能会激活以处理自定义 URI 协议或文件(附带注册应用以处理的扩展名)。Or it may be activated to handle a custom URI protocol or a file with an extension that your app is registered to handle. 有关可激活应用的方法的列表,请参阅 ActivationKindFor a list of ways your app can be activated, see ActivationKind.

Windows.UI.Xaml.Application 类定义可替代以处理各种应用激活方法的方法。The Windows.UI.Xaml.Application class defines methods you can override to handle the various ways your app may be activated. OnActivated 可以处理所有可能的激活类型。OnActivated can handle all possible activation types. 但是,更常见的做法是使用特定方法来处理最常见的激活类型,而对于不太常见的激活类型,则使用 OnActivated 作为回滚方法。However, it's more common to use specific methods to handle the most common activation types, and use OnActivated as the fallback method for the less common activation types. 有其他方法可用于特定激活:These are the additional methods for specific activations:

OnCachedFileUpdaterActivatedOnCachedFileUpdaterActivated
OnFileActivatedOnFileActivated
OnFileOpenPickerActivated OnFileSavePickerActivatedOnFileOpenPickerActivated OnFileSavePickerActivated
OnSearchActivatedOnSearchActivated
OnShareTargetActivatedOnShareTargetActivated

这些方法的事件数据包含我们之前所见的相同 PreviousExecutionState 属性,这会告诉你应用在激活之前处于哪种状态。The event data for these methods includes the same PreviousExecutionState property that we saw above, which tells you which state your app was in before it was activated. 解释状态以及应该对它采取的操作,方法与上面应用启动部分中所述的方法相同。Interpret the state and what you should do it the same way as described above in the App launch section.

注意  如果使用计算机的管理员帐户登录,则无法激活 UWP 应用。Note If you log on using the computer's Administrator account, you can't activate UWP apps.

在后台运行Running in the background

从 Windows 10 版本 1607 开始,应用可以在应用本身所在的同一进程内运行后台任务。Starting with Windows 10, version 1607, apps can run background tasks within the same process as the app itself. 有关详细信息,请参阅单个进程的后台活动模型Read more about it in Background activity with the Single Process Model. 在本文中,我们不会介绍进程内后台处理,但会介绍这如何影响应用生命周期:已添加与应用何时处于后台有关的两个新的事件。We won't go into in-process background processing in this article, but how this impacts the app lifecycle is that two new events have been added related to when your app is in the background. 事件如下:EnteredBackgroundLeavingBackgroundThey are: EnteredBackground and LeavingBackground.

这些事件还反映用户是否可以看到你的应用的 UI。These events also reflect whether the user can see your app's UI.

Running in the background 是应用程序启动、激活或恢复后所处的默认状态。Running in the background is the default state that an application is launched, activated, or resumed into. 在此状态中,应用程序 UI 尚不可见。In this state your application UI is not visible yet.

Running in the foregroundRunning in the foreground

Running in the foreground 意味着应用 UI 可见。Running in the foreground means that your app's UI is visible.

只在应用程序 UI 可见之前和进入 Running in foreground 状态之前,才会引发 LeavingBackground 事件。The LeavingBackground event is fired just before your application UI is visible and before entering the running in foreground state. 还会在用户切换回应用时引发该事件。It also fires when the user switches back to your app.

以前,用于加载 UI 资源的最佳位置是在 ActivatedResuming 事件处理程序中。Previously, the best location to load UI assets was in the Activated or Resuming event handlers. 现在,LeavingBackground 是用于验证 UI 是否准备就绪的最佳位置。Now LeavingBackground is the best place to verify that your UI is ready.

请务必在此时检查可视化资源是否已准备就绪,因为这是应用程序对用户可见之前执行此操作的最后机会。It is important to check that visual assets are ready by this time because this is the last opportunity to do work before your application is visible to the user. 适用于此事件处理程序的所有 UI 都应快速完成,因为会影响用户体验的启动和恢复时间。All UI work in this event handler should complete quickly, as it impacts the launch and resume time that the user experiences. LeavingBackground 用于确保 UI 的第一帧已准备就绪时。LeavingBackground is the time to ensure the first frame of UI is ready. 然后,应该异步处理长时间运行的存储或网络调用,以便事件处理程序可能会返回。Then, long-running storage or network calls should be handled asynchronously so that the event handler may return.

当用户离开应用程序时,应用会重新进入 Running in background 状态。When the user switches away from your application, your app reenters the running in background state.

重新进入后台状态Reentering the background state

EnteredBackground 事件表明应用在前台不再可见。The EnteredBackground event indicates that your app is no longer visible in the foreground. EnteredBackground 在最小化应用时(在台式计算机上)引发,而在切换到主屏幕或另一个应用时(在手机上)引发。On the desktop EnteredBackground fires when your app is minimized; on phone, when switching to the home screen or another app.

减少应用的内存使用量Reduce your app's memory usage

由于应用对用户不再可见,因此这是用于停止 UI 呈现工作和动画的最佳位置。Since your app is no longer visible to the user, this is the best place to stop UI rendering work and animations. 可以使用 LeavingBackground 重新开始这项工作。You can use LeavingBackground to start that work again.

如果要在后台工作,可在此位置做好相关准备。If you are going to do work in the background, this is the place to prepare for it. 最好是检查 MemoryManager.AppMemoryUsageLevel(如果需要)并减少应用正在使用的内存使用量(当应用在后台运行时),以便应用不会冒遭系统释放资源而被终止的风险。It is best to check MemoryManager.AppMemoryUsageLevel and, if needed, reduce the amount of memory being used by your app when it is running in the background so that your app doesn't risk being terminated by the system to free up resources.

有关更多详细信息,请参阅在应用移动到后台状态时减少内存使用量See Reduce memory usage when your app moves to the background state for more details.

保存状态Save your state

suspending 事件处理程序是保存应用状态的最佳位置。The suspending event handler is the best place to save your app state. 但是,如果你要在后台工作(例如,音频播放、使用扩展的执行会话或进程内后台任务),在 EnteredBackground 事件处理程序中以异步方式保存你的数据也是好的做法。However, if you are doing work in the background (for example, audio playback, using an extended execution session or in-proc background task), it is also a good practice to save your data asynchronously from your EnteredBackground event handler. 这是因为,当应用以较低优先级处于后台时可能会被终止。This is because it is possible for your app to be terminated while it is at a lower priority in the background. 而且由于应用在此情况下并不会经历 suspended 状态,因此会丢失数据。And because the app will not have gone through the suspended state in that case, your data will be lost.

在后台活动开始之前,在 EnteredBackground 事件处理程序中保存你的数据,以确保用户将应用重新返回前台时可获得良好的用户体验。Saving your data in your EnteredBackground event handler, before background activity begins, ensures a good user experience when the user brings your app back to the foreground. 可以使用应用程序数据 API 保存数据和设置。You can use the application data APIs to save data and settings. 有关详细信息,请参阅存储和检索设置以及其他应用数据For more info, see Store and retrieve settings and other app data.

保存你的数据后,如果超出内存使用量限制,可以从内存中释放你的数据(因为可以稍后重新加载它)。After you save your data, if you are over your memory usage limit, then you can release your data from memory since you can reload it later. 这将释放内存,释放的内存可供后台活动所需的资源使用。That will free memory that can be used by the assets needed for background activity.

请注意,如果你的应用在进程中具有后台活动,则应用可能会从 Running in the background 状态转变为 Running in the foreground 状态,而不曾经历 suspended 状态。Be aware that if your app has background activity in progress that it can move from the running in the background state to the running in the foreground state without ever reaching the suspended state.

异步工作和延迟Asynchronous work and Deferrals

如果在处理程序中执行异步调用,控件将立即从该异步调用中返回。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.

如果需要更多时间来保存状态,请调查用于在应用进入后台状态之前的阶段保存状态的方法,以便减少在 EnteredBackground 事件处理程序中用于保存的时间。If you need more time to save your state, investigate ways to save your state in stages before your app enters the background state so that there is less to save in your EnteredBackground event handler. 或者可以请求 ExtendedExecutionSession 获取更多时间。Or you may request an ExtendedExecutionSession to get more time. 由于并不能保证该请求得到允许,因此最好是找到方法来最大程度地减少保存状态所需的时间量。There is no guarantee that the request will be granted, however, so it is best to find ways to minimize the amount of time you need to save your state.

应用暂停App suspend

当用户最小化某个应用时,Windows 会等待数秒,以查看用户是否会切换回该应用。When the user minimizes an app Windows waits a few seconds to see whether the user will switch back to it. 如果用户在此时间范围内未切换回,并且任何扩展执行、后台任务或活动赞助执行都未处于活动状态,则 Windows 将暂停该应用。If they do not switch back within this time window, and no extended execution, background task, or activity sponsored execution is active, Windows suspends the app. 只要应用中不存在任何处于活动状态的扩展执行会话等,该应用也将在出现锁屏界面时暂停。An app is also suspended when the lock screen appears as long as no extended execution session, etc. is active in that app.

当暂停应用时,它将调用 Application.Suspending 事件。When an app is suspended, it invokes the Application.Suspending event. Visual Studio 的 UWP 项目模板为在 App.xaml.cs 中称为 OnSuspending 的此事件提供处理程序。Visual Studio’s UWP project templates provide a handler for this event called OnSuspending in App.xaml.cs. 在 Windows 10 版本 1607 之前,要在此处添加用于保存状态的代码。Prior to Windows 10, version 1607, you would put the code to save your state here. 现在建议在进入后台状态时保存状态,如上所述。Now the recommendation is to save your state when you enter the background state, as described above.

你应释放独占资源和文件句柄,以便其他应用可以在你的应用暂停时访问它们。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.

注意截止时间Be aware of the deadline

为了确保设备的快速响应,对你用于在 suspending 事件处理程序中运行代码的时间有限制。In order to ensure a fast and responsive device, there is a limit for the amount of time you have to run your code in your suspending event handler. 此限制因设备而异,你可以使用称为截止时间的 SuspendingOperation 对象的属性来查明其数值。It is different for each device, and you can find out what it is using a property of the SuspendingOperation object called the deadline.

EnteredBackground 事件处理程序来说,如果在处理程序中执行异步调用,控件将立即从该异步调用中返回。As with the EnteredBackground event handler, if you make an asynchronous call from 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 suspend state even though the asynchronous call hasn't completed yet. 使用 SuspendingOperation 对象(可通过事件参数获取)上的 GetDeferral 方法延迟进入 suspended 状态,直到调用返回的 SuspendingDeferral 对象上的 Complete 方法。Use the GetDeferral method on the SuspendingOperation object (available via the event args) to delay entering the suspended state until after you call the Complete method on the returned SuspendingDeferral object.

如果需要更多时间,可以请求 ExtendedExecutionSessionIf you need more time, you may request an ExtendedExecutionSession. 由于并不能保证该请求得到允许,因此最好是找到方法最大程度地减少在 Suspended 事件处理程序中需要的时间量。There is no guarantee that the request will be granted, however, so it is best to find ways to minimize the amount of time you need in your Suspended event handler.

应用终止App terminate

当你的应用暂停时,系统会尝试将你的应用及其数据保留在内存中。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, it will terminate your app. 应用不会收到它们被终止的通知,所以你只能将应用数据保存在 OnSuspension 事件处理程序中,或者在 EnteredBackground 处理程序中以异步方式保存。Apps don't receive a notification that they are being terminated, so the only opportunity you have to save your app's data is in your OnSuspension event handler, or asynchronously from your EnteredBackground handler.

当应用确定它在终止后被激活时,它应该加载它保存的应用程序数据,以使应用处于与其终止之前相同的状态。When your app determines that it has been activated after being terminated, it should load the application data that it saved so that the app is in the same state it was in before it was terminated. 当用户切换回已终止的暂停应用时,该应用应该在其 OnLaunched 方法中还原其应用程序数据。When the user switches back to a suspended app that has been terminated, the app should restore its application data in its OnLaunched method. 当终止应用时系统不会通知应用,因此在暂停应用之前,你的应用必须保存其应用程序数据并释放独占资源和文件句柄,并且当在终止后又激活应用时还原这些内容。The system doesn't notify an app when it is terminated, so your app must save its application data and release exclusive resources and file handles before it is suspended, and restore them when the app is activated after termination.

有关使用 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.

应用恢复App resume

如果用户切换到应用或当设备从低功耗状态恢复时该应用是活动的应用,将恢复暂停的应用。A suspended app is resumed when the user switches to it or when it is the active app when the device comes out of a low power state.

当应用从 Suspended 状态恢复时,它会进入 Running in background 状态,系统将应用恢复到它离开时的状态,以使用户感觉该应用好像一直在运行。When an app is resumed from the Suspended state, it enters the Running in background state and the system restores the app where it left off so that it appears to the user as if it has been running all along. 不会丢失存储在内存中的任何应用数据。No app data stored in memory is lost. 因此,大多数应用在恢复时并不需要恢复状态(尽管它们应该重新获取它们在被暂停时释放的任何文件或设备句柄),也不需要恢复该应用被暂停时显式释放的任何状态。Therefore, most apps don't need to restore state when they are resumed though they should reacquire any file or device handles that they released when they were suspended, and restore any state that was explicitly released when the app was suspended.

应用可能会暂停数小时或数天。You app may be suspended for hours or days. 如果应用具有可能已过时的内容或网络连接,这些内容或网络连接应该在应用恢复时刷新。If your app has content or network connections that may have gone stale, these should be refreshed when the app resumes. 如果应用已为 Application.Resuming 事件注册一个事件处理程序,则在应用从 Suspended 状态恢复时调用它。If an app registered an event handler for the Application.Resuming event, it is called when the app is resumed from the Suspended state. 可以在该事件处理程序中刷新应用内容和数据。You can refresh your app content and data in this event handler.

如果激活暂停的应用以加入一个应用合约或扩展,它会首先收到 Resuming 事件,然后收到 Activated 事件。If a suspended app is activated to participate in an app contract or extension, it receives the Resuming event first, then the Activated event.

如果暂停的应用已终止,则不存在任何 Resuming 事件,将改为使用 TerminatedApplicationExecutionState 调用 OnLaunched()If the suspended app was terminated, there is no Resuming event and instead OnLaunched() is called with an ApplicationExecutionState of Terminated. 由于在暂停应用时保存了状态,因此可以在 OnLaunched() 期间恢复该状态,以使应用对用户来说好像它处于用户离开它时的状态。Because you saved your state when the app was suspended, you can restore that state during OnLaunched() so that your app appears to the user as it was when they switched away from it.

当应用暂停时,它不会收到它注册用于接收的任何网络事件。While an app is suspended, it does not receive any network events that it registered to receive. 这些网络事件没有排队,它们只是丢失了。These network events are not queued--they are simply missed. 因此,你的应用应该在恢复时测试网络状态。Therefore, your app should test the network status when it is resumed.

注意   由于不会从 UI 线程中引发恢复事件,因此,如果恢复处理程序中的代码与 ui 通信,则必须使用调度程序。Note  Because the Resuming event is not raised from the UI thread, a dispatcher must be used if the code in your resume handler communicates with your UI. 请参阅从后台线程更新 UI 线程以获取有关如何执行此操作的代码示例。See Update the UI thread from a background thread for a code example of how to do this.

有关一般准则,请参阅应用暂停和恢复指南For general guidelines, see Guidelines for app suspend and resume.

应用关闭App close

通常,用户不需要关闭应用,他们可以让 Windows 管理它们。Generally, users don't need to close apps, they can let Windows manage them. 但是,用户可以选择以下方法来关闭应用:使用关闭手势、按 Alt+F4,或在 Windows Phone 上使用任务切换程序。However, users can choose to close an app using the close gesture or by pressing Alt+F4 or by using the task switcher on Windows Phone.

没有事件指示用户关闭了应用。There is not an event to indicate that the user closed the app. 当用户关闭应用时,应用首先处于暂停状态,以使你有机会保存其状态。When an app is closed by the user, it is first suspended to give you an opportunity to save its state. 在 Windows 8.1 和更高版本中,在用户关闭应用之后,该应用将从屏幕和切换列表中删除,但不会显式终止。In Windows 8.1 and later, after an app has been closed by the user, the app is removed from the screen and switch list but not explicitly terminated.

按用户关闭的行为:   如果在用户关闭应用程序时,应用程序关闭时需要执行其他操作,则可以使用激活事件处理程序来确定应用程序是由用户还是由 Windows 终止。Closed-by-user behavior:  If your app needs to do something different when it is closed by the user than when it is closed by Windows, you can use the activation event handler to determine whether the app was terminated by the user or by Windows. 请参阅 ApplicationExecutionState 枚举的参考中 ClosedByUserTerminated 状态的说明。See the descriptions of ClosedByUser and Terminated states in the reference for the ApplicationExecutionState enumeration.

我们建议,应用不要以编程方式自行关闭,除非绝对必要。We recommend that apps not close themselves programmatically unless absolutely necessary. 例如,如果应用检测到内存泄漏,它可以关闭自身来确保用户个人数据的安全性。For example, if an app detects a memory leak, it can close itself to ensure the security of the user's personal data.

应用崩溃App crash

系统故障体验旨在使用户尽快返回他们当时正在执行的操作。The system crash experience is designed to get users back to what they were doing as quickly as possible. 不应提供警告对话框或其他通知,因为这会给用户带来延迟。You shouldn't provide a warning dialog or other notification because that will delay the user.

如果应用出现故障、停止响应或者发生意外,系统将通过用户的反馈和诊断设置向 Microsoft 发送问题报告。If your app crashes, stops responding, or generates an exception, a problem report is sent to Microsoft per the user's feedback and diagnostics settings. Microsoft 在问题报告中向你提供错误数据的一个子集,这样你可以使用这些数据改进你的应用。Microsoft provides a subset of the error data in the problem report to you so that you can use it to improve your app. 你可以在“仪表板”中应用的“质量”页面中看到此数据。You'll be able to see this data in your app's Quality page in your Dashboard.

当用户在应用发生崩溃之后激活该应用时,其激活事件处理程序将收到 NotRunningApplicationExecutionState 值,并且应显示其初始 UI 和数据。When the user activates an app after it crashes, its activation event handler receives an ApplicationExecutionState value of NotRunning, and should display its initial UI and data. 崩溃后,不要经常使用原本将用于 ResumingSuspended 的应用数据,因为该数据可能已损坏;请参阅应用暂停和恢复指南After a crash, don't routinely use the app data you would have used for Resuming with Suspended because that data could be corrupt; see Guidelines for app suspend and resume.

应用删除App removal

当用户删除你的应用时,会一同删除应用及其所有本地数据。When a user deletes your app, the app is removed, along with all its local data. 删除应用不会影响存储在公用位置的用户数据,例如“文档”或“图片库”。Removing an app doesn't affect the user's data that was stored in common locations such as the Documents or Pictures libraries.

应用生命周期和 Visual Studio 项目模板App lifecycle and the Visual Studio project templates

在 Visual Studio 项目模板中提供与应用生命周期相关的基本代码。The basic code that is relevant to the app lifecycle is provided in the Visual Studio project templates. 基本应用可处理启动激活、为你提供还原应用数据的位置,甚至可以在你添加任何自己的代码之前显示主要 UI。The basic app handles launch activation, provides a place for you to restore your app data, and displays the primary UI even before you've added any of your own code. 有关详细信息,请参阅适用于应用的 C#、VB 和 C++ 项目模板For more info, see C#, VB, and C++ project templates for apps.

关键应用程序生命周期 APIKey application lifecycle APIs