使用背景工作支援應用程式Support your app with background tasks

本節中的主題將示範如何在背景中執行輕量型程式碼來回應觸發程序。The topics in this section show you how to make lightweight code run in the background in response to triggers. 您可以使用背景工作,在 app 被暫停或未執行時提供功能。You can use background tasks to provide functionality when your app is suspended or not running. 您也可以將背景工作用於即時通訊 App,像是 VOIP、郵件和 IM。You can also use background tasks for real-time communication apps like VOIP, mail, and IM.

在背景播放媒體Playing media in the background

從 Windows 10 版本 1607 開始,在背景播放音訊變得更加容易。Starting in Windows 10, version 1607, playing audio in the background is much easier. 如需詳細資訊,請參閱在背景播放媒體See Play media in the background for more information.

同處理序與跨處理序背景工作In-process and out-of-process background tasks

有兩種執行背景工作的方法:There are two approaches to implementing background tasks:

  • 同處理序:App 及其背景處理程序在同一個處理序中執行In-process: the app and its background process run in the same process
  • 跨處理序:App 及其背景處理程序在不同的處理序中執行。Out-of-process: the app and the background process run in separate processes.

同處理序背景支援是在 Windows 10 版本 1607 中引進,用來簡化背景工作的撰寫。In-process background support was introduced in Windows 10, version 1607, to simplify writing background tasks. 但是您仍然可以撰寫跨處理程序工作。But you can still write out-of-process background tasks. 如需有關撰寫同處理程序與跨處理程序背景工作的時機建議,請參閱背景工作指導方針See Guidelines for background tasks for recommendations on when to write an in-process versus out-of-process background task.

跨處理序背景工作的復原性較佳,因為如果發生錯誤,背景處理程序無法關閉您的 App 處理序。Out-of-process background tasks are more resilient because the background process can't bring down your app process if something goes wrong. 但復原性的代價是在 App 與背景工作之間管理跨處理序通訊的複雜度變高。But the resiliency comes at the price of greater complexity to manage the cross-process communication between the app and the background task.

跨處理序背景工作實作為實作 IBackgroundTask 介面的輕量型類別,而這個介面會由作業系統在個別處理序 (backgroundtaskhost.exe) 中執行。Out-of-process background tasks are implemented as lightweight classes that implement the IBackgroundTask interface that the OS runs in a separate process (backgroundtaskhost.exe). 使用 BackgroundTaskBuilder 類別來註冊背景工作。Register a background task by using the BackgroundTaskBuilder class. 在登錄背景工作時,類別名稱可用來指定進入點。The class name is used to specify the entry point when you registering the background task.

在 Windows 10 版本 1607 中,您可以在不建立背景工作的情況下啟用背景活動。In Windows 10, version 1607, you can enable background activity without creating a background task. 您可以改為直接在前景應用程式的處理序內執行背景程式碼。You can instead run your background code directly inside the foreground application's process.

若要快速開始使用同處理序背景工作,請參閱建立和註冊同處理序背景工作To get started quickly with in-process background tasks, see Create and register an in-process background task.

若要快速開始使用跨處理序背景工作,請參閱建立及註冊跨處理序背景工作To get started quickly with out-of-process background tasks, see Create and register an out-of-process background task.

提示

 從 Windows 10 開始,您已不再需要將 App 放在鎖定畫面上,就可以為其註冊背景工作。 Starting with Windows 10, you no longer need to place an app on the lock screen as a prerequisite for registering a background task for it.

系統事件的背景工作Background tasks for system events

您的應用程式可以藉由使用 SystemTrigger 類別登錄背景工作的方式,回應系統產生的事件。Your app can respond to system-generated events by registering a background task with the SystemTrigger class. App 可以使用下列任何系統事件觸發程序 (於 SystemTriggerType 中定義)An app can use any of the following system event triggers (defined in SystemTriggerType)

觸發程序名稱Trigger name 描述Description
InternetAvailableInternetAvailable 網際網路變成可用。The Internet becomes available.
NetworkStateChangeNetworkStateChange 網路變更,例如發生費用或連線變更。A network change such as a change in cost or connectivity occurs.
OnlineIdConnectedStateChangeOnlineIdConnectedStateChange 與帳戶關聯的線上識別碼變更。Online ID associated with the account changes.
SmsReceivedSmsReceived 安裝的行動式寬頻裝置收到新的 SMS 訊息。A new SMS message is received by an installed mobile broadband device.
TimeZoneChangeTimeZoneChange 裝置時區變更 (例如,系統因為日光節約時間而調整時鐘)。The time zone changes on the device (for example, when the system adjusts the clock for daylight saving time).

如需詳細資料,請參閱使用背景工作回應系統事件For more info see Respond to system events with background tasks.

背景工作的條件Conditions for background tasks

您可以新增條件來控制背景工作執行的時間,即使是觸發後也可以。You can control when the background task runs, even after it is triggered, by adding a condition. 觸發之後,背景工作會等到所有條件都符合才執行。Once triggered, a background task will not run until all of its conditions are met. 以下為可以使用的條件 (以 SystemConditionType 列舉表示)。The following conditions (represented by the SystemConditionType enumeration) can be used.

條件名稱Condition name 說明Description
InternetAvailableInternetAvailable 網際網路必須為可用。The Internet must be available.
InternetNotAvailableInternetNotAvailable 網際網路必須為無法使用。The Internet must be unavailable.
SessionConnectedSessionConnected 工作階段必須已連線。The session must be connected.
SessionDisconnectedSessionDisconnected 工作階段必須已中斷連線。The session must be disconnected.
UserNotPresentUserNotPresent 使用者必須是離開狀態。The user must be away.
UserPresentUserPresent 使用者必須是上線狀態。The user must be present.

新增 InternetAvailable 條件至您的背景工作 BackgroundTaskBuilder.AddCondition 可延遲觸發背景工作,直到網路堆疊執行。Add the InternetAvailable condition to your background task BackgroundTaskBuilder.AddCondition to delay triggering the background task until the network stack is running. 這個條件可以節省電源,因為直到網路可用前,背景工作都不會執行。This condition saves power because the background task won't execute until the network is available. 這個條件不提供即時啟動。This condition does not provide real-time activation.

如果您的背景工作需要網路連線,請設定 IsNetworkRequested 以確保在背景工作執行時保持網路連線。If your background task requires network connectivity, set IsNetworkRequested to ensure that the network stays up while the background task runs. 這會告訴背景工作基礎結構在工作執行時隨時保持網路連線,即使裝置已進入 [連線待命] 模式。This tells the background task infrastructure to keep the network up while the task is executing, even if the device has entered Connected Standby mode. 如果您的背景工作未設定 IsNetworkRequested,則在連線待命模式下,您的背景工作將無法存取網路 (例如,當手機的螢幕關閉時。 )  If your background task does not set IsNetworkRequested, then your background task will not be able to access the network when in Connected Standby mode (for example, when a phone's screen is turned off.)   如需背景工作條件的詳細資訊,請參閱設定執行背景工作的條件For more info about background task conditions, see Set conditions for running a background task.

應用程式資訊清單需求Application manifest requirements

您必須先在應用程式資訊清單中宣告 App,App 才能成功註冊在跨處理序中執行的背景工作。Before your app can successfully register a background task that runs out-of-process, it must be declared in the application manifest. 背景工作如果是在與其主控 App 相同的處理序中執行,您就不需要在應用程式資訊清單中宣告。Background tasks that run in the same process as their host app do not need to be declared in the application manifest. 如需詳細資訊,請參閱在應用程式資訊清單中宣告背景工作For more info see Declare background tasks in the application manifest.

背景工作Background tasks

下列即時觸發程序可用來在背景執行輕量型自訂程式碼:The following real-time triggers can be used to run lightweight custom code in the background:

即時觸發程序Real-time trigger 說明Description
控制通道Control Channel 背景工作可以保持連線,並透過使用 ControlChannelTrigger 在控制通道上接收訊息。Background tasks can keep a connection alive, and receive messages on the control channel, by using the ControlChannelTrigger. 如果您的 App 正在接聽通訊端,則您可以使用「通訊端代理程式」,而不使用 ControlChannelTriggerIf your app is listening to a socket, you can use the Socket Broker instead of the ControlChannelTrigger. 如需使用通訊端代理程式的詳細資訊,請參閱 SocketActivityTriggerFor more details on using the Socket Broker, see SocketActivityTrigger. Windows Phone 不支援 ControlChannelTriggerThe ControlChannelTrigger is not supported on Windows Phone.
計時器Timer 背景工作的執行頻率最高可達每 15 分鐘一次,而且只要使用 TimeTrigger 即可設定在特定時間執行。Background tasks can run as frequently as every 15 minutes, and they can be set to run at a certain time by using the TimeTrigger. 如需詳細資訊,請參閱在計時器上執行背景工作For more info see Run a background task on a timer.
推播通知Push Notification 背景工作會回應 PushNotificationTrigger 以接收原始推播通知。Background tasks respond to the PushNotificationTrigger to receive raw push notifications.

注意Note  

通用 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, call RemoveAccess and then call RequestAccessAsync when your app launches after being updated. 如需詳細資訊,請參閱背景工作的指導方針For more information, see Guidelines for background tasks.

觸發程序執行個體的數目限制: App 可以註冊某些觸發程序的執行個體數目有限制。Limits on the number of trigger instances: There are limits to how many instances of some triggers an app can register. App 只能針對其每個執行個體註冊 ApplicationTriggerMediaProcessingTriggerDeviceUseTrigger 一次。An app can only register ApplicationTrigger, MediaProcessingTrigger and DeviceUseTrigger once per instance of the app. 如果 App 超過此限制,註冊將會擲回例外狀況。If an app goes over this limit, registration will throw an exception.

系統事件觸發程序System event triggers

SystemTriggerType 列舉代表下列系統事件觸發程序:The SystemTriggerType enumeration represents the following system event triggers:

觸發程序名稱Trigger name 描述Description
UserPresentUserPresent 背景工作會在使用者變成存在時觸發。The background task is triggered when the user becomes present.
UserAwayUserAway 背景工作會在使用者變成不在時觸發。The background task is triggered when the user becomes absent.
ControlChannelResetControlChannelReset 背景工作會在控制通道重設時觸發。The background task is triggered when a control channel is reset.
SessionConnectedSessionConnected 背景工作會在工作階段連線時觸發。The background task is triggered when the session is connected.

  下列系統事件觸發程序會在使用者將 App 移入或移出鎖定畫面時發出訊號。The following system event triggers signal when the user has moved an app on or off the lock screen.

觸發程序名稱Trigger name 描述Description
LockScreenApplicationAddedLockScreenApplicationAdded App 磚已新增到鎖定畫面。An app tile is added to the lock screen.
LockScreenApplicationRemovedLockScreenApplicationRemoved App 磚已從鎖定畫面移除。An app tile is removed from the lock screen.

 

背景工作資源限制Background task resource constraints

背景工作為輕量型。Background tasks are lightweight. 將背景執行降至最低可確保不論是在前景 App 還是電池使用時間上,使用者都能獲得最佳體驗。Keeping background execution to a minimum ensures the best user experience with foreground apps and battery life. 這是透過將資源限制套用至背景工作來強制執行。This is enforced by applying resource constraints to background tasks.

背景工作的使用時間是限制為 30 秒時鐘時間。Background tasks are limited to 30 seconds of wall-clock usage.

記憶體限制Memory constraints

由於低記憶體裝置的資源限制,因此背景工作可能會有記憶體限制,此限制會決定背景工作所能使用的記憶體量上限。Due to the resource constraints for low-memory devices, background tasks may have a memory limit that determines the maximum amount of memory the background task can use. 如果您的背景工作嘗試執行會超出這個限制的作業,該作業將會失敗,而可能會產生該工作可以處理的記憶體不足例外狀況。If your background task attempts an operation that would exceed this limit, the operation will fail and may generate an out-of-memory exception--which the task can handle. 如果該工作無法處理記憶體不足例外狀況,或所嘗試之作業的本質導致未產生記憶體不足例外狀況,則該工作將會立即終止。If the task does not handle the out-of-memory exception, or the nature of the attempted operation is such that an out-of-memory exception was not generated, then the task will be terminated immediately.

您可以使用 MemoryManager API 查詢目前的記憶體使用量及限制以探索您的最高限度 (如果有的話),並且監視您的背景工作正在進行的記憶體使用量。You can use the MemoryManager APIs to query your current memory usage and limit in order to discover your cap (if any), and to monitor your background task's ongoing memory usage.

低記憶體裝置針對具有背景工作的應用程式的個別裝置限制Per-device limit for apps with background tasks for low-memory devices

在記憶體受限的裝置上,會限制可安裝在裝置上的 app 數量以及在任何指定時間可使用背景工作的 app 數量。On memory-constrained devices, there is a limit to the number of apps that can be installed on a device and use background tasks at any given time. 如果超過這個數字,對 RequestAccessAsync 的呼叫 (登錄所有背景工作時所需進行的呼叫) 就會失敗。If this number is exceeded, the call to RequestAccessAsync, which is required to register all background tasks, will fail.

省電模式Battery Saver

除非您豁免您的 App,使其在省電模式開啟時,仍然可以執行背景工作並接收推播通知,否則當電池省電功能啟用時,只要裝置沒有連接外部電源,而且電池電量低於指定的剩餘電量,它就會阻止背景工作執行。Unless you exempt your app so that it can still run background tasks and receive push notifications when Battery Saver is on, the Battery Saver feature, when enabled, will prevent background tasks from running when the device is not connected to external power and the battery goes below a specified amount of power remaining. 但是不會阻止您登錄背景工作。This will not prevent you from registering background tasks.

不過,對於企業應用程式,以及將不會在 Microsoft Store 發佈的應用程式,請參閱 在背景無限期執行 ,以瞭解如何在背景無限期地使用功能來執行背景工作或擴充執行會話。However, for enterprise apps, and apps that will not be published in the Microsoft Store, see Run in the background indefinitely to learn how to use a capabilities to run a background task or extended execution session in the background indefinitely.

即時通訊的背景工作資源保證Background task resource guarantees for real-time communication

為了防止資源配額干擾即時通訊功能,使用 ControlChannelTriggerPushNotificationTrigger 之背景工作的每個執行中工作都會收到保證的 CPU 資源配額。To prevent resource quotas from interfering with real-time communication functionality, background tasks using the ControlChannelTrigger and PushNotificationTrigger receive guaranteed CPU resource quotas for every running task. 資源配額如以上所述,並且在這些背景工作會保持不變。The resource quotas are as mentioned above, and remain constant for these background tasks.

針對 ControlChannelTriggerPushNotificationTrigger 背景工作,您的 app 不必執行其他動作就可以取得保證的資源配額。Your app doesn't have to do anything differently to get the guaranteed resource quotas for ControlChannelTrigger and PushNotificationTrigger background tasks. 系統永遠都會將這些視為極為重要的背景工作。The system always treats these as critical background tasks.

維護觸發程序Maintenance trigger

維護工作只有在裝置插入 AC 電源時才能執行。Maintenance tasks only run when the device is plugged in to AC power. 如需詳細資訊,請參閱使用維護觸發程序For more info see Use a maintenance trigger.

感應器和裝置的背景工作Background tasks for sensors and devices

您的 App 可以使用 DeviceUseTrigger 類別,從背景工作存取感應器和週邊裝置。Your app can access sensors and peripheral devices from a background task with the DeviceUseTrigger class. 您可以在長時間執行的操作使用這個觸發程序,例如資料同步或監控。You can use this trigger for long-running operations such as data synchronization or monitoring. 與系統事件的工作不同,DeviceUseTrigger 工作只能在您的 App 於前景中執行時觸發,而且您不能對它設定任何條件。Unlike tasks for system events, a DeviceUseTrigger task can only be triggered while your app is running in the foreground and no conditions can be set on it.

重要

DeviceUseTriggerDeviceServicingTrigger 無法與同處理序背景工作搭配使用。The DeviceUseTrigger and DeviceServicingTrigger cannot be used with in-process background tasks.

部分重要裝置操作 (例如長時間執行的韌體更新) 無法使用 DeviceUseTrigger 來執行。Some critical device operations, such as long running firmware updates, cannot be performed with the DeviceUseTrigger. 這類操作只能在電腦上執行,而且只能由使用 DeviceServicingTrigger 且具有特殊權限的 App 來執行。Such operations can be performed only on the PC, and only by a privileged app that uses the DeviceServicingTrigger. 具有特殊權限的 App」是裝置製造商授權執行這些操作的 App。A privileged app is an app that the device's manufacturer has authorized to perform those operations. 裝置中繼資料可用來指定要將哪個應用程式 (如果有的話) 指定為裝置的具有特殊權限的應用程式。Device metadata is used to specify which app, if any, has been designated as the privileged app for a device. 如需詳細資訊,請參閱 Microsoft Store 裝置應用程式的裝置同步與更新For more info, see Device sync and update for Microsoft Store device apps

管理背景工作Managing background tasks

背景工作可使用事件與本機存放裝置向您的 app 報告進度、完成與取消。Background tasks can report progress, completion, and cancellation to your app using events and local storage. 您的 app 也可抓取由背景工作擲回的例外狀況,並在 app 更新期間管理背景工作登錄。Your app can also catch exceptions thrown by a background task, and manage background task registration during app updates. 如需詳細資訊,請參閱:For more info see:

處理已取消的背景工作Handle a cancelled background task
監視背景工作進度和完成Monitor background task progress and completion

在 App 啟動期間檢查背景工作註冊。Check your background task registration during app launch. 確定 BackgroundTaskBuilder.AllTasks 中有 App 未分組的背景工作。Ensure that your app's ungrouped background tasks are present in BackgroundTaskBuilder.AllTasks. 重新註冊不在其中的背景工作。Re-register the ones that are not present. 取消註冊任何不再需要的工作。Unregister any tasks that are no longer needed. 這可確保每次啟動 App 時,所有背景工作註冊都是最新的。This ensures that all background tasks registrations are up-to-date every time the app is launched.

在 Windows 10 中執行多工的概念指引Conceptual guidance for multitasking in Windows 10

相關的背景工作指導方針Related background task guidance