使用后台任务支持应用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. 你可以使用后台任务在应用暂停或未运行时提供功能。You can use background tasks to provide functionality when your app is suspended or not running. 也可以将后台任务用于实时通信应用,例如 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:

  • 进程内:应用与其后台进程在同一进程内运行In-process: the app and its background process run in the same process
  • 进程外:应用与后台进程在不同进程中运行。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.

进程外后台任务更容易复原,因为在出现错误时,后台进程不会使应用崩溃。Out-of-process background tasks are more resilient because the background process can't bring down your app process if something goes wrong. 但复原的代价是应用与后台任务之间的跨进程通信管理更为复杂。But the resiliency comes at the price of greater complexity to manage the cross-process communication between the app and the background task.

进程外后台任务实现为轻型类,该类实现操作系统在独立进程 (backgroundtaskhost.exe) 中运行的 IBackgroundTask 接口。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 开始,无需将应用放置在锁屏界面上以充当为该应用注册后台任务的先决条件。 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. 应用可以使用以下任意系统事件触发器(在 SystemTriggerType 中定义)An app can use any of the following system event triggers (defined in SystemTriggerType)

触发器名称Trigger name 说明Description
InternetAvailableInternetAvailable Internet 变为可用。The Internet becomes available.
NetworkStateChangeNetworkStateChange 网络更改,如开销或连接性发生更改。A network change such as a change in cost or connectivity occurs.
OnlineIdConnectedStateChangeOnlineIdConnectedStateChange 与帐户更改关联的联机 ID。Online ID associated with the account changes.
SmsReceivedSmsReceived 安装的移动宽带设备收到一条新短信。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 Internet 必须可用。The Internet must be available.
InternetNotAvailableInternetNotAvailable Internet 必须不可用。The Internet must be unavailable.
SessionConnectedSessionConnected Internet 必须连接。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

在应用成功注册可以在进程外运行的后台任务前,必须在应用程序清单中声明该任务。Before your app can successfully register a background task that runs out-of-process, it must be declared in the application manifest. 在与主机应用运行的相同进程中运行的后台任务无需在应用程序清单中声明。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. 如果你的应用正在侦听套接字,可以使用套接字代理而不是 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. ControlChannelTrigger 在 Windows Phone 上不受支持。The 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 应用必须在注册任何后台触发器类型之前调用 RequestAccessAsyncUniversal Windows apps must call RequestAccessAsync before registering any of the background trigger types.

若要确保通用 Windows 应用在你发布更新后继续正常运行,请在启动已经过更新的应用时调用 RemoveAccess,然后调用 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.

限制触发器实例数: 应用可注册的某些触发器的实例数存在限制。Limits on the number of trigger instances: There are limits to how many instances of some triggers an app can register. 对于应用的每个实例,应用只能注册一次 ApplicationTriggerMediaProcessingTriggerDeviceUseTriggerAn app can only register ApplicationTrigger, MediaProcessingTrigger and DeviceUseTrigger once per instance of the 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.

  以下系统事件触发器将指示用户何时将应用移到或移出锁屏界面。The following system event triggers signal when the user has moved an app on or off the lock screen.

触发器名称Trigger name 说明Description
LockScreenApplicationAddedLockScreenApplicationAdded 向锁屏中添加应用磁贴。An app tile is added to the lock screen.
LockScreenApplicationRemovedLockScreenApplicationRemoved 从锁屏中删除应用磁贴。An app tile is removed from the lock screen.

 

后台任务资源限制Background task resource constraints

后台任务时轻型的。Background tasks are lightweight. 使后台执行保持在最低程度可确保前台应用和电池使用时间的最佳用户体验。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 PAI 查询当前内存使用量和限制,以发现上限(若有),并监视正在进行的后台任务内存使用量。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

在内存受限的设备上,对于可以安装在一台设备上并在任何给定时间使用后台任务的应用数量有所限制。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. 如果超出该数量,将无法调用注册所有后台任务时所需的 RequestAccessAsyncIf this number is exceeded, the call to RequestAccessAsync, which is required to register all background tasks, will fail.

节电模式Battery Saver

除非你豁免你的应用,以便它可以在节电模式打开时仍可以运行后台任务和接收推送通知,否则当节电模式功能启用时,如果设备未连接到外部电源且电量低于指定剩余电量,它将阻止后台任务运行。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 后台任务的保证资源配额。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

维护任务仅在设备插入到交流电源时才会运行。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

你的应用可以使用 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 任务仅在你的应用在前台运行且在其上无法设置任何条件时触发。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 的特权应用执行。Such operations can be performed only on the PC, and only by a privileged app that uses the DeviceServicingTrigger. 特权应用是指由设备制造商授权执行这些操作的应用。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

后台任务可以使用事件和本地存储向你的应用报告进度、完成和取消。Background tasks can report progress, completion, and cancellation to your app using events and local storage. 你的应用还可以捕捉由后台任务引发的异常,并在应用更新过程中管理后台任务注册。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

在应用启动期间检查你的后台任务注册。Check your background task registration during app launch. 确保你的应用的未分组后台任务显示在 BackgroundTaskBuilder.AllTasks 中。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. 这可确保每次应用启动时所有后台任务注册都是最新的。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