创建和注册进程内后台任务Create and register an in-process background task

重要的 APIImportant APIs

本主题演示了如何创建和注册在你的应用所在的同一进程中运行的后台任务。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. 如果在进程内后台任务中运行的代码崩溃,这将降低你的应用的性能。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.

请注意,如果后台活动的运行时间超过执行时间限制,即使在应用的前台进程内运行,后台活动也会终止。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

进程内模型可通过应用在前台运行还是在后台运行的改进通知增强应用程序生命周期。The in-process model enhances the application lifecycle with improved notifications for when your app is in the foreground or in the background. 对于这些过渡,Application 对象提供了两个新事件:EnteredBackgroundLeavingBackgroundTwo new events are available from the Application object for these transitions: EnteredBackground and LeavingBackground. 基于你的应用程序的可见性状态,这些事件适合应用程序生命周期。在应用生命周期中阅读有关这些事件的详细信息,以及它们如何影响应用程序生命周期。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 事件以运行将在应用在后台运行时执行的代码,处理 LeavingBackground 以了解应用何时移至前台。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 应用必须在注册任何后台触发器类型之前调用 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, 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,这将在注册之后的十五分钟引发。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. 例如,如果你不希望在用户存在前运行任务,请使用条件 UserPresentFor 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.Run 进行处理。OnBackgroundActivated 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 示例,请参阅 将应用服务转换为在与其主机应用相同的进程中运行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

可使用用于多进程后台任务的相同方式监视任务进度和完成(请参阅监视后台任务进度和完成),但你可能会发现,通过使用变量跟踪你的应用中的进度或完成状态,可更轻松地跟踪它们。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. 这是在你的应用所在的同一进程中运行后台活动代码的优势之一。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 引用、后台任务概念指南以及编写使用后台任务的应用的更多详细说明,请参阅以下相关主题。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