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

重要 APIImportant APIs

本主題示範如何建立和註冊與您的 App 在相同處理序中執行的背景工作。This topic demonstrates how to create and register a background task that runs in the same process as your app.

實作同處理序背景工作比實作跨處理序背景工作簡單。In-process background tasks are simpler to implement than out-of-process background tasks. 不過,前者較不具彈性。However, they are less resilient. 如果在同處理序背景工作中執行的程式碼損毀,將會關閉您的 App。If the code running in an in-process background task crashes, it will take down your app. 另請注意,DeviceUseTriggerDeviceServicingTriggerIoTStartupTask 無法與同處理序模型搭配使用。Also note that DeviceUseTrigger, DeviceServicingTrigger and IoTStartupTask cannot be used with the in-process model. 此外,也不可能在應用程式內啟用 VoIP 背景工作。Activating a VoIP background task within your application is also not possible. 使用跨處理序背景工作模型仍可支援這些觸發程序和工作。These triggers and tasks are still supported using the out-of-process background task model.

請注意,如果背景活動在執行時超過執行時間限制,則即使它是在 App 的前景處理序內執行,也可能被終止。Be aware that background activity can be terminated even when running inside the app's foreground process if it runs past execution time limits. 就某些用途而言,將工作分散到在個別處理程序中執行的背景工作中仍然相當有用。For some purposes the resiliency of separating work into a background task that runs in a separate process is still useful. 對於不需要與前景應用程式進行通訊的工作來說,將背景工作保持為與前景應用程式分開的工作可能是最佳選項。Keeping background work as a task separate from the foreground application may be the best option for work that does not require communication with the foreground application.

基礎Fundamentals

同處理序模型藉由提供 App 進入前景或背景時的改良式通知,增強應用程式週期。The in-process model enhances the application lifecycle with improved notifications for when your app is in the foreground or in the background. 應用程式物件針對這些轉換提供兩個新的事件:EnteredBackgroundLeavingBackgroundTwo new events are available from the Application object for these transitions: EnteredBackground and LeavingBackground. 這些事件適用的應用程式週期取決於應用程式的可見度狀態。如需了解這些事件及它們如何影響應用程式週情,請參閱 App 週期These events fit into the application lifecycle based on the visibility state of your application Read more about these events and how they affect the application lifecycle at App lifecycle.

大致說來,您將處理 EnteredBackground 事件來執行將在您 App 於背景中執行時執行的程式碼,以及處理 LeavingBackground 以在您 App 已移至前景時能夠得知。At a high level, you will handle the EnteredBackground event to run your code that will execute while your app is running in the background, and handle LeavingBackground to know when your app has moved to the foreground.

註冊背景工作觸發程序Register your background task trigger

註冊同處理序背景活動的方式與註冊跨處理序背景活動的方式非常相似。In-process background activity is registered much the same as out-of-process background activity. 所有背景觸發程序都是先使用 BackgroundTaskBuilder 進行註冊。All background triggers start with registration using the BackgroundTaskBuilder. 建立器可讓您在一個地方設定所有必要的值,讓您輕輕鬆鬆就可以登錄背景工作︰The builder makes it easy to register a background task by setting all required values in one place:

var builder = new BackgroundTaskBuilder();
builder.Name = "My Background Trigger";
builder.SetTrigger(new TimeTrigger(15, true));
// Do not set builder.TaskEntryPoint for in-process background tasks
// Here we register the task and work will start based on the time trigger.
BackgroundTaskRegistration task = builder.Register();

注意

通用 Windows app 必須先呼叫 RequestAccessAsync,才能登錄任何背景觸發程序類型。Universal Windows apps must call RequestAccessAsync before registering any of the background trigger types. 為了確保您的通用 Windows app 會在您發行更新之後繼續正常執行,您必須呼叫 RemoveAccess,然後在 app 於更新後啟動時呼叫 RequestAccessAsyncTo ensure that your Universal Windows app continues to run properly after you release an update, you must call RemoveAccess and then call RequestAccessAsync when your app launches after being updated. 如需詳細資訊,請參閱背景工作的指導方針For more information, see Guidelines for background tasks.

針對同處理序背景活動,您將不設定 TaskEntryPoint.。將它留白會啟用預設進入點,這是 Application 物件上一個受保護的新方法,稱為 OnBackgroundActivated()For in-process background activities you do not set TaskEntryPoint. Leaving it blank enables the default entry point, a new protected method on the Application object called OnBackgroundActivated().

登錄觸發程序之後,它就會根據 SetTrigger 方法中所設定的觸發程序類型引發。Once a trigger is registered, it will fire based on the type of trigger set in the SetTrigger method. 在上述範例中,使用的是 TimeTrigger,會在登錄它之後 15 分鐘引發。In the example above a TimeTrigger is used, which will fire fifteen minutes from the time it was registered.

新增條件來控制工作執行時機 (選擇性)Add a condition to control when your task will run (optional)

您可以新增條件來控制觸發程序事件發生後工作的執行時機。You can add a condition to control when your task will run after the trigger event occurs. 例如,如果您希望等到使用者在場時才執行工作,可以使用 UserPresent 條件。For example, if you don't want the task to run until the user is present, use the condition UserPresent. 如需可用條件的清單,請參閱 SystemConditionTypeFor a list of possible conditions, see SystemConditionType.

下列範例程式碼會指派條件,要求必須要有使用者:The following sample code assigns a condition requiring the user to be present:

builder.AddCondition(new SystemCondition(SystemConditionType.UserPresent));

將您的背景活動程式碼放在 OnBackgroundActivated() 中Place your background activity code in OnBackgroundActivated()

將您的背景活動程式碼放在 OnBackgroundActivated 中,以在引發時回應背景觸發程式。Put your background activity code in OnBackgroundActivated to respond to your background trigger when it fires. OnBackgroundActivated 可以視同 IBackgroundTask.RunOnBackgroundActivated can be treated just like IBackgroundTask.Run. 方法具有 BackgroundActivatedEventArgs 參數,其中包含 Run 方法提供的所有專案。The method has a BackgroundActivatedEventArgs parameter, which contains everything that the Run method delivers. 例如,在 App.xaml.cs 中:For example, in App.xaml.cs:

using Windows.ApplicationModel.Background;

...

sealed partial class App : Application
{
  ...

  protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
  {
      base.OnBackgroundActivated(args);
      IBackgroundTaskInstance taskInstance = args.TaskInstance;
      DoYourBackgroundWork(taskInstance);  
  }
}

如需更豐富的 OnBackgroundActivated 範例,請參閱 轉換 app service 以在其主機應用程式的相同進程中執行For a richer OnBackgroundActivated example, see Convert an app service to run in the same process as its host app.

處理背景工作進度和完成Handle background task progress and completion

監視工作進度和完成的方式與監視多處理程序背景工作的方式相同 (請參閱監視背景工作進度和完成),但是您可能會發現透過在 App 中使用變數來追蹤進度或完成狀態更加容易。Task progress and completion can be monitored the same way as for multi-process background tasks (see Monitor background task progress and completion) but you will likely find that you can more easily track them by using variables to track progress or completion status in your app. 這是讓背景活動在與 App 相同的處理程序中執行的其中一個優點。This is one of the advantages of having your background activity code running in the same process as your app.

處理背景工作取消Handle background task cancellation

取消同處理序背景工作的方式與取消跨處理序背景工作的方式相同 (請參閱處理已取消的背景工作)。In-process background tasks are cancelled the same way as out-of-process background tasks are (see Handle a cancelled background task). 請注意,在發生取消之前,您的 BackgroundActivated 事件處理常式必須先結束,否則系統會終止整個處理程序。Be aware that your BackgroundActivated event handler must exit before the cancellation occurs, or the whole process will be terminated. 如果您的前景應用程式在您取消背景工作時意外關閉,請確認您的處理常式是否在發生取消之前已結束。If your foreground app closes unexpectedly when you cancel the background task, verify that your handler exited before the cancellation occured.

資訊清單The manifest

與跨處理序背景工作不同,您不需要將背景工作資訊新增到套件資訊清單中,即可執行同處理序背景工作。Unlike out-of-process background tasks, you are not required to add background task information to the package manifest in order to run in-process background tasks.

摘要和後續步驟Summary and next steps

您現在應該對如何撰寫同處理序背景工作有基本的了解。You should now understand the basics of how to write a in-process background task.

請參閱下列 API 參考的相關主題、背景工作概念指引,以及撰寫使用背景工作之 app 的更詳細說明。See the following related topics for API reference, background task conceptual guidance, and more detailed instructions for writing apps that use background tasks.

詳細的背景工作教學主題Detailed background task instructional topics

背景工作指引Background task guidance

背景工作 API 參考Background Task API Reference