在更新 UWP 應用程式時執行背景工作Run a background task when your UWP app is updated

了解如何在更新通用 Windows 平台 (UWP) 市集應用程式之後寫入背景工作。Learn how to write a background task that runs after your Universal Windows Platform (UWP) store app is updated.

「更新工作」背景工作是在使用者安裝已安裝於裝置之 App 的更新之後,由作業系統叫用。The Update Task background task is invoked by the operating system after the user installs an update to an app that is installed on the device. 這可讓 App 在使用者啟動更新的 App 之前執行初始化工作,例如初始化新的推播通知通道、更新資料庫結構描述等工作。This allows your app to perform initialization tasks such as initializing a new push notification channel, updating database schema, and so on, before the user launches your updated app.

「更新工作」不同於使用 ServicingComplete 觸發程序啟動背景工作,因為在此情況下,您的 App 就必須在更新之前執行至少一次,才能註冊將會由 ServicingComplete 觸發程序啟動的背景工作。The Update Task differs from launching a background task using the ServicingComplete trigger because in that case your app must run at least once before it is updated in order to register the background task that will be activated by the ServicingComplete trigger. 「更新工作」未註冊,也因此從未執行 App,若不是升級,仍將觸發其更新工作。The Update Task isn't registered and so an app that has never been run, but that is upgraded, will still have its update task triggered.

步驟 1:建立背景工作類別Step 1: Create the background task class

與其他類型的背景工作一樣,您會將「更新工作」背景工作實作為 Windows 執行階段元件。As with other types of background tasks, you implement the Update Task background task as a Windows Runtime component. 若要建立此元件,請依照建立和註冊跨處理序背景工作「建立背景工作類別」 一節中的步驟進行。To create this component, follow the steps in the Create the Background Task class section of Create and register an out-of-process background task. 步驟包括:The steps include:

  • 將 Windows 執行階段元件專案加入至方案。Adding a Windows Runtime component project to your solution.
  • 從 App 建立元件的參考。Creating a reference from your app to the component.
  • 在實作 IBackgroundTask 的元件中建立公用密封類別。Creating a public, sealed class in the component that implements IBackgroundTask.
  • 實作 Run 方法,這是在執行「更新工作」時呼叫的必要進入點。Implementing the Run method, which is the required entry point that is called when the Update Task is run. 如果您要從背景工作進行非同步呼叫,建立和註冊跨處理序背景工作 會說明如何在 Run 方法中使用延遲。If you are going to make asynchronous calls from your background task, Create and register an out-of-process background task explains how to use a deferral in your Run method.

您不需要註冊此背景工作 (「建立和註冊跨處理序背景工作」 主題中的「註冊要執行的背景工作」一節),就能使用「更新工作」。You don't need to register this background task (the "Register the background task to run" section in the Create and register an out-of-process background task topic) to use the Update Task. 這就是使用「更新工作」的主要原因,因為您不需要新增任何程式碼至 App 來註冊背景工作,而且 App 不必在更新之前至少執行一次,也能註冊背景工作。This is the main reason to use an Update Task because you don't need to add any code to your app to register the task and the app doesn't have to at least run once before being updated to register the background task.

下列範例程式碼使用 C# 示範「更新工作」背景工作類別的基本起點:The following sample code shows a basic starting point for a Update Task background task class in C#. 背景工作類別本身 (及背景工作專案中的所有其他類別) 必須是 publicsealedThe background task class itself - and all other classes in the background task project - need to be public and sealed. 背景工作類別必須衍生自 IBackgroundTask,並且具有如下所示簽章的公用 Run() 方法:Your background task class must derive from IBackgroundTask and have a public Run() method with the signature shown below:

using Windows.ApplicationModel.Background;

namespace BackgroundTasks
{
    public sealed class UpdateTask : IBackgroundTask
    {
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // your app migration/update code here
        }
    }
}

步驟 2:在封裝資訊清單中宣告背景工作Step 2: Declare your background task in the package manifest

在 Visual Studio 方案總管中,以滑鼠右鍵按一下 Package.appxmanifest,然後按一下**[檢視程式碼]** 以檢視封裝資訊清單。In the Visual Studio Solution Explorer, right-click Package.appxmanifest and click View Code to view the package manifest. 新增下列 <Extensions> XML 來宣告更新工作:Add the following <Extensions> XML to declare your update task:

<Package ...>
    ...
  <Applications>  
    <Application ...>  
        ...
      <Extensions>  
        <Extension Category="windows.updateTask"  EntryPoint="BackgroundTasks.UpdateTask">  
        </Extension>  
      </Extensions>

    </Application>  
  </Applications>  
</Package>

在上述 XML 中,確定 EntryPoint 屬性已設定為更新工作的 namespace.class 名稱。In the XML above, ensure that the EntryPoint attribute is set to the namespace.class name of your update task class. 名稱區分大小寫。The name is case-sensitive.

步驟 3:偵錯/測試更新工作Step 3: Debug/test your Update task

確定您已將 App 部署到電腦,讓其中有要更新的項目。Ensure that you have deployed your app to your machine so that there is something to update.

設定背景工作之 Run() 方法的中斷點。Set a breakpoint in the Run() method of your background task.

設定中斷點

接下來,在方案總管中,以滑鼠右鍵按一下 App 的專案 (而非背景工作專案),然後按一下**[屬性]**。Next, in the solution explorer, right-click your app's project (not the background task project) and then click Properties. 在應用程式的屬性視窗中,按一下左側的 [偵錯],然後選取 [不啟動,但在我的程式碼啟動時進行偵錯]In the application Properties window, click Debug on the left, then select Do not launch, but debug my code when it starts:

設定偵錯設定

接下來,為了確保 UpdateTask 已觸發,請增加封裝的版本號碼。Next, to ensure that the UpdateTask is triggered, increase the package's version number. 在 [方案總管] 中,按兩下 App 的 Package.appxmanifest 檔案開啟封裝設計工具,然後更新組建編號:In the Solution Explorer, double-click your app's Package.appxmanifest file to open the package designer, and then update the Build number:

更新版本

現在,在 Visual Studio 2019 中,當您按下 F5 時,將會更新您的應用程式,而且系統會在背景中啟動您的 UpdateTask 元件。Now, in Visual Studio 2019 when you press F5, your app will be updated and the system will activate your UpdateTask component in the background. 偵錯工具會自動連結到背景處理程序。The debugger will automatically attach to the background process. 觸及中斷點後,您即可逐步檢查更新程式碼邏輯。Your breakpoint will get hit and you can step through your update code logic.

背景工作完成時,就可以在相同偵錯工作階段中,從 Windows [開始] 功能表啟動前景 App。When the background task completes, you can launch the foreground app from the Windows start menu within the same debug session. 偵錯工具會再次自動連結,但這次是連結到前景處理程序,您可以逐步檢查 App 的邏輯。The debugger will again automatically attach, this time to your foreground process, and you can step through your app's logic.

注意

Visual Studio 2015 使用者:上述步驟適用于 Visual Studio 2017 或 Visual Studio 2019。Visual Studio 2015 users: The above steps apply to Visual Studio 2017 or Visual Studio 2019. 如果使用的是 Visual Studio 2015,除了 Visual Studio 不會連結到 UpdateTask 之外,您都可以使用相同的技術來觸發和測試它。If you are using Visual Studio 2015, you can use the same techniques to trigger and test the UpdateTask, except Visual Studio will not attach to it. VS 2015 中的替代程序是設定 ApplicationTrigger,這會將 UpdateTask 設定為其進入點,並直接從前景 App 觸發執行。An alternative procedure in VS 2015 is to setup an ApplicationTrigger that sets the UpdateTask as its Entry Point, and trigger the execution directly from the foreground app.

另請參閱See also

建立及註冊跨處理序的背景工作Create and register an out-of-process background task