處理應用程式暫停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 事件,它會指示 app 必須在系統暫停 app 之前,儲存自己的應用程式資料。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

當您的 app 處理 Suspending 事件時,它有機會在處理常式函式中儲存自己的重要應用程式資料。When your app handles the Suspending event, it has the opportunity to save its important application data in the handler function. App 必須使用 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

您應該釋放獨占資源及檔案控制代碼,這樣當您的 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.

備註Remarks

當使用者切換至另一個 app、桌面或 [開始] 畫面時,系統會暫停您的 app。The system suspends your app whenever the user switches to another app or to the desktop or Start screen. 當使用者切換回您的 app 時,系統就會繼續執行 app。The system resumes your app whenever the user switches back to it. 當系統繼續執行您的 app 時,您的變數和資料結構內容和系統暫停 app 之前一樣,沒有變化。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. 系統會將 app 回復成暫停之前的相同狀態,如此使用者會以為 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.

當 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, the system will terminate your app. 當使用者切換回已被終止的暫停 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.

系統不會在 app 終止時提供通知,所以 app 必須在暫停時儲存應用程式資料並釋放獨占資源及檔案控制代碼,並在終止狀態結束後重新啟用時還原這些項目。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. 這表示執行可隨後從事件處理常式傳回,即使非同步呼叫尚未完成,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. 若要延長暫停狀態的時間,請使用 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. 為了支援這個新的優先順序,會延長暫停作業逾時,在 Windows 上讓 app 與標準優先順序一樣擁有 5 秒逾時,或在 Windows Phone 上有介於 1 到 10 秒之間的逾時。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. 這是為了讓使用者在 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.