Windows 10 通用 Windows 平台 (UWP) app 週期Windows 10 universal Windows platform (UWP) app lifecycle

本主題描述通用 Windows 平台 (UWP) app 從啟動到關閉為止的整個週期。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 推出前,app 的週期很簡單。Before Windows 8, apps had a simple lifecycle. Win32 與.NET app 不是在執行中,就是並未執行。Win32 and .NET apps are either running or not running. 當使用者將它們縮至最小或切換到其他 app 時,它們會繼續執行。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 app 會在使用者將其縮至最小或切換到其他應用程式時,很快暫停。A UWP app is suspended shortly after the user minimizes it or switches to another app. 這表示 app 的執行緒會停止,而且除非作業系統需要回收資源,否則會將 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. 當使用者切換回 app 時,它會快速還原到正在執行的狀態。When the user switches back to the app, it can be quickly restored to a running state.

當 app 在背景時,需要繼續執行的的 app 會有各種不同的形態,像是背景工作延伸執行及活動贊助執行 (例如,允許 app 繼續在背景播放媒體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). 此外,即使您的 app 已遭到暫停或甚至終止時,背景傳輸作業仍會繼續執行。Also, background transfer operations can continue even if your app is suspended or even terminated. 如需詳細資訊,請參閱如何下載檔案For more info, see How to download a file.

根據預設,不在前景的 app 會暫停,藉以產生省電效果,並讓目前在前景 app 有更多的資源可用。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.

對於身為開發人員的您而言,因為作業系統可能會選擇終止暫停的 app 以釋出資源,所以暫停的狀態會增加新的需求。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. 工具列中仍會顯示終止的 app。The terminated app will still appear in the task bar. 因為使用者不會注意到系統已將 app 關閉,所以當使用者按一下 app 時,app 必須將其還原至終止之前的狀態。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. 他們會認為 app 始終在背景中等待使用者做別的事,並預期 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 執行狀態App execution state

這個圖例表示一開始在 Windows 10 (版本 1607) 中可能的 app 模型狀態。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.

狀態圖例,顯示 app 執行狀態之間的轉換

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. 讓我們先來看看啟動 app。Let's first look at launching an app.

App 啟動App launch

App 啟動時,會呼叫 OnLaunched 方法。The OnLaunched method is called when an app is launched. 傳遞所提供的 LaunchActivatedEventArgs 參數,一起傳遞到 app 的其他項目,還有引數、磚 (啟動該應用程式) 的識別碼,以及先前的 app 狀態。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.

從會傳回 ApplicationExecutionStateLaunchActivatedEventArgs.PreviousExecutionState,取得 app 先前的狀態。Get 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 自使用者上次重新開機或登入之後,都未曾啟動的 app 可能會處於這個狀態。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. 如同第一次在目前的使用者工作階段中執行一般,將 app 初始化。Initialize the app as if it is running for the first time in the current user session.
Suspended 使用者將 app 最小化或切換到其他 app,卻未在數秒內返回。The user either minimized or switched away from your app and didn't return to it within a few seconds. App 暫停時,其狀態仍留在記憶體中。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 App 先前遭到暫停,但之後卻在某個時間點因為系統需要回收記憶體而遭到關閉。The app was previously suspended but was then shutdown at some point because the system needed to reclaim memory. 還原到使用者離開 app 時的狀態。Restore the state that the app was in when the user switched away from it.
ClosedByUserClosedByUser 使用者在平板電腦模式中,利用關閉手勢或 Alt+F4 關閉 app。The user closed the app with the close gesture in tablet mode, or with Alt+F4. 當使用者關閉 app 時,其會遭到暫停,然後才予以終止。When the user closes the app, it is first suspended and then terminated. 因為 app 基本上都是經由相同步驟進入 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 當使用者嘗試再次啟動時,app 早已開啟。The app was already open when the user tried to launch it again. 無。Nothing. 請注意,並不會啟動另一個 app 執行個體。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. 

但有一個重要的情況需要注意,如果裝置有足夠的資源,作業系統會預先啟動經常使用且已選擇加入該行為的 app,以讓回應性達到最佳。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. 預先啟動的 app 會在背景啟動,隨後迅速暫停,以便使用者切換至該 app 時,以比啟動 app 更快的速度繼續。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.

由於會預先啟動,所以會由系統初始化 app 的 OnLaunched() 方法,而不是使用者。Because of prelaunch, the app’s OnLaunched() method may be initiated by the system rather than by the user. 因為 app 是在背景預先啟動,所以您需要採取的動作可能和 OnLaunched() 不同。Because the app is prelaunched in the background you may need to take different action in OnLaunched(). 例如,如果您的 app 會在啟動時開始播放音樂,因為已在背景預先載入 app,所以並不會知道其來自何處。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. 在背景預先啟動 app 之後,隨即會呼叫 Application.SuspendingOnce your app is prelaunched in the background, it is followed by a call to Application.Suspending. 然後會在使用者實際啟動 app 時,叫用繼續事件以及 OnLaunched() 方法。Then, when the user does launch the app, the resuming event is invoked as well as the OnLaunched() method. 如需有關如何處理預先啟動案例的詳細資訊,請參閱處理 app 預先啟動See Handle app prelaunch for additional information about how to handle the prelaunch scenario. 只有選擇加入的 app 才會預先啟動。Only apps that opt-in are prelaunched.

Windows 會在 app 啟動時顯示啟動顯示畫面。Windows displays a splash screen for the app when it is launched. 如果要設定啟動顯示畫面,請參閱新增啟動顯示畫面To configure the splash screen, see Adding a splash screen.

顯示啟動顯示畫面時,app 應登錄事件處理常式,並設定初始頁面所需的任何自訂 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() 會在數秒 內完成,否則系統可能會認為 app 已停止回應而予以終止。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. 如果 app 必須從網路取得資料,或必須從磁碟抓取大量資料,那麼您應該在啟動以外的時間完成這些動作。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. App 可以使用自己的自訂載入 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.

App 完成啟動之後會進入 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 啟用App activation

和由使用者啟動相反,app 也可以由系統啟用。In contrast to being launched by the user, an app can be activated by the system. App 可由協定啟用,例如分享協定。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. 如需可用以啟用 app 的方式清單,請參閱ActivationKindFor a list of ways your app can be activated, see ActivationKind.

Windows.UI.Xaml.Application 類別定義您可以覆寫以處理各種不同 app 啟用方式的方法。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. 解譯狀態以及您同樣應採取的方式,如上面的 App 啟動一節中所述。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 開始,app 可以在與 app 本身相同的處理序內執行背景工作。Starting with Windows 10, version 1607, apps can run background tasks within the same process as the app itself. 如需深入瞭解,請參閱 Background activity with the Single Process Model (單一處理序模型的背景活動)Read more about it in Background activity with the Single Process Model. 我們將不會在本文中談及同處理序背景處理,但這對 app 週期的影響是新增兩個和 app 在背景時有關的新事件。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.

這些事件也會反映出使用者是否能看到 app 的 UI。These events also reflect whether the user can see your app's UI.

在背景執行是應用程式已啟動、啟用,或繼續執行的預設狀態。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 foreground

在前景執行表示可以見到 app 的 UI。Running in the foreground means that your app's UI is visible.

在可看到您的應用程式的 UI 之前,以及在進入前景執行之前,都會觸發 LeavingBackground 事件。The LeavingBackground event is fired just before your application UI is visible and before entering the running in foreground state. 還有當使用者切換回到您的 app 時也會觸發。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.

當使用者切換到其他應用程式時,您的 app 會重新進入在背景執行的狀態。When the user switches away from your application, your app reenters the running in background state.

重新進入背景狀態Reentering the background state

EnteredBackground 事件指出 app 已不會再出現在前景。The EnteredBackground event indicates that your app is no longer visible in the foreground. 桌面會在 app 縮到最小時觸發 EnteredBackground,而手機會在切換到主畫面或另一個應用程式時觸發。On the desktop EnteredBackground fires when your app is minimized; on phone, when switching to the home screen or another app.

減少 app 的記憶體使用量Reduce your app's memory usage

由於使用者已看不見 app,最好於此停止 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,並視需要減少 app 在背景中執行時的記憶體使用量,避免 app 遭到系統終止以釋出資源。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.

如需詳細資訊,請參閱減少當 app 移至背景狀態時的記憶體使用量See Reduce memory usage when your app moves to the background state for more details.

儲存您的狀態Save your state

暫停的事件處理常式會是儲存 app 狀態的最佳位置。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. 這是因為 app 可能會在背景中以低優先順序執行時遭到終止。This is because it is possible for your app to be terminated while it is at a lower priority in the background. 此外,因為在上述情況中,app 並不會進入暫停狀態,而將使您的資料遺失。And because the app will not have gone through the suspended state in that case, your data will be lost.

在背景活動開始之前,先在 EnteredBackground 事件處理常式中儲存資料,可確保使用者將 app 帶回到前景時獲得良好的使用者經驗。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.

請注意,如果您的 app 有進行中的背景活動,其會不進入暫停狀態,直接從在背景執行的狀態變成在前景執行的狀態。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. 這表示執行可隨後從事件處理常式傳回,即使非同步呼叫尚未完成,app 也會移至下一個狀態。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.

如果您需要更多時間來儲存狀態,請調查在 app 進入背景狀態之前的階段儲存狀態的做法,這樣要在 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 暫停App suspend

當使用者將 app 縮至最小時,Windows 會先等候幾秒鐘,看使用者是否會切換回 app。When the user minimizes an app Windows waits a few seconds to see whether the user will switch back to it. 如果沒有在這個時間範圍內切換回來,也沒有任何延伸執行、背景工作或活動贊助執行在使用中,Windows 就會暫停該 app。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. 當鎖定畫面出現時,只要該 app 中沒有延伸執行工作階段等在使用中,也同樣會暫停 app。An app is also suspended when the lock screen appears as long as no extended execution session, etc. is active in that app.

當 app 暫停時,其會叫用 Application.Suspending 事件。When an app is suspended, it invokes the Application.Suspending event. Visual Studio 的 UWP 專案範本為此事件在 App.xaml.cs 中提供的處理常式稱為 OnSuspendingVisual 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.

您應該釋放獨占資源及檔案控制代碼,這樣當您的 app 暫停時,其他 app 仍然可以使用它們。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. 明確釋放獨占資源及檔案控制代碼,有助於確保當您的 app 暫停時,其他 app 仍然可以使用它們。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

為了確保裝置運作快速且有回應,因此在暫停事件處理常式中執行程式碼的時間長度會有限制。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. 這表示執行可隨後從事件處理常式傳回,即使非同步呼叫尚未完成,app 也會移至暫停狀態。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 方法,來延遲進入暫停狀態,直到您針對傳回的 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 終止App terminate

當 app 暫停時,系統會嘗試讓 app 及其資料保留在記憶體中。The system attempts to keep your app and its data in memory while it's suspended. 不過,如果系統沒有資源可將 app 保存在記憶體中,便會終止您的 app。However, if the system does not have the resources to keep your app in memory, it will terminate your app. App 不會收到它們遭到終止的通知,因此,您唯一可以儲存 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.

當 app 判斷它在遭到終止後又再度啟用時,應該會載入所儲存的應用程式資料,以讓 app 處於和終止之前相同的狀態。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. 當使用者切換回遭到終止的暫停 app 時,app 應該在其 OnLaunched 方法中還原自己的 app 資料。When the user switches back to a suspended app that has been terminated, the app should restore its application data in its OnLaunched method. 系統不會在 app 終止時提供通知,所以 app 必須在暫停之前儲存應用程式資料並釋放獨占資源及檔案控制代碼,並在終止狀態結束後再次啟用時還原這些項目。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. 這是為了讓使用者在 app 執行時可以檢視 Visual Studio 偵錯 UI。This is to allow the user to view the Visual Studio debug UI while the app is running. 當您正在對某個 app 偵錯時,您可以使用 Visual Studio 傳送一個暫停事件給該 app。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 繼續執行App resume

當使用者切換到暫停的 app,或當裝置脫離電源不足的狀態時,使用中的正好是該 app,暫停的 app 就可以繼續執行。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.

當 app 從 Suspended 狀態繼續執行時,會進入 「在背景執行」 狀態,而系統會將 app 還原至先前使用者離開時的狀態,如此使用者會以為 app 一直在執行中。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. 儲存在記憶體中的 app 資料都不會遺失。No app data stored in memory is lost. 因此,大部分應用程式繼續執行時都不需要還原狀態,但是都應該重新取得在暫停時所釋出的任何檔案或裝置控制代碼,並將 app 暫停時明確釋出的任何狀態還原。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.

您的 app 可能會暫停長達數小時或數天。You app may be suspended for hours or days. 如果 app 的內容或網路連線已過時,應要在 app 繼續執行時重新整理。If your app has content or network connections that may have gone stale, these should be refreshed when the app resumes. 如果 app 已登錄 Application.Resuming 事件的事件處理常式,當 app 從 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. 您可以在這個事件處理常式內重新整理 app 的內容和資料。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.

如果暫停的應用程式已經終止,就不會有 繼續 事件,而改以 TerminatedApplicationExecutionState 來呼叫 OnLaunched()If the suspended app was terminated, there is no Resuming event and instead OnLaunched() is called with an ApplicationExecutionState of Terminated. 因為您已在 app 暫停時儲存狀態,所以您可以在 OnLaunched() 期間還原該狀態,如此使用者會以為 app 一直維持在使用者切換到其他 app 時的狀態。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.

當 app 遭到暫停時,它不會接收到原先登錄要接收的任何網路事件。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. 因此,您的 app 在繼續時必須測試網路狀態。Therefore, your app should test the network status when it is resumed.

請注意  , 因為繼續的事件不是從 ui 執行緒引發, 所以如果您的 resume 處理常式中的程式碼與您的 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.

如需一般指導方針,請參閱 App 暫停和繼續執行的指導方針For general guidelines, see Guidelines for app suspend and resume.

App 關閉App close

使用者通常不需要關閉 app,交由 Windows 管理即可。Generally, users don't need to close apps, they can let Windows manage them. 不過,使用者可以在 Windows Phone 上,選擇使用關閉手勢,或按 Alt+F4 或使用工作切換器,來關閉 app。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.

沒有事件可指出使用者已關閉 app。There is not an event to indicate that the user closed the app. 由使用者關閉 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 關閉, 您可以使用啟用事件處理常式來判斷應用程式是否由使用者或 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.

建議您除非絕對有必要,否則不要讓 app 以程式設計的方式自行關閉。We recommend that apps not close themselves programmatically unless absolutely necessary. 例如,如果 app 偵測到記憶體流失,就可以自行關閉以保護使用者個人資料的安全。For example, if an app detects a memory leak, it can close itself to ensure the security of the user's personal data.

App 毀損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.

如果您的 app 毀損、停止回應或產生例外狀況,系統將會依據使用者的意見反應與診斷設定將問題報告傳送給 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 會在給您的問題報告中提供錯誤資料的子集,讓您用來改善 app。Microsoft provides a subset of the error data in the problem report to you so that you can use it to improve your app. 您可以在您的儀表板中 app 的 [品質] 頁面上看到這些資料。You'll be able to see this data in your app's Quality page in your Dashboard.

當使用者在 app 毀損之後再次啟用,其啟用事件處理常式會收到 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 的方式使用 app 資料,因為該資料可能已經損毀,請參閱 App 暫停和繼續執行的指導方針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 移除App removal

當使用者刪除 app 後,app 會連同所有本機資料一併移除。When a user deletes your app, the app is removed, along with all its local data. 移除 app 並不會影響儲存在常見位置中的使用者資料,例如文件庫或圖片庫。Removing an app doesn't affect the user's data that was stored in common locations such as the Documents or Pictures libraries.

App 週期與 Visual Studio 專案範本App lifecycle and the Visual Studio project templates

Visual Studio 專案範本中會提供與 app 週期相關的基本程式碼。The basic code that is relevant to the app lifecycle is provided in the Visual Studio project templates. 基本的 app 會處理啟動的啟用,提供一個讓您可以還原 app 資料的位置,甚至可在您新增自己的程式碼之前,顯示其主要的 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. 如需詳細資訊,請參閱 App 的 C#、VB 及 C++ 專案範本For more info, see C#, VB, and C++ project templates for apps.

重要的應用程式週期 APIKey application lifecycle APIs