标签:
一、介绍
1、多任务处理
什么是多任务处理?它意味着当App被挂起时,它仍然可以完成一些开发者设定的任务,比如更新tiles和toasts、预定toast和提醒、后台任务等。
2、后台任务
App可以注册后台任务,它被系统运行和管理,但它依旧使用和前台程序一样的数据储存等,同时它使用的CPU资源是由系统限制的。它可以使用toast, tile, badge UI等。一个App可以注册使用多个后台任务。
二、添加后台任务
1、添加一个新的项目到解决方案中作为后台任务,如图
然后,添加以下类似代码(重点是添加IBackgroundTask)
public sealed class TheTask : IBackgroundTask { public void Run(IBackgroundTaskInstance taskInstance) { var deferral = taskInstance.GetDeferral(); taskInstance.canceled+=(s,e)=>{};//当后台任务被限制执行时触发事件 taskInstance.Progress = 0;//后台任务的进度 deferral.Complete(); }
2、后台任务触发设置(在前台程序,不是在TheTask)
后台任务将根据触发器是否被触发而运行,以下是多种触发器:
同时也可以添加条件,让后台任务根据条件运行,可以设置一下几种条件等
添加条件代码很简单,代码如下:
3、在manifest声明 中,添加后台任务声明
4、请求及注册后台任务(在前台程序中)
async void RegisterBackgroundTasks() { // On Windows, RequestAccessAsync presents the user with a confirmation // dialog that requests that an app be allowed on the lock screen. // On Windows Phone, RequestAccessAsync does not show any user confirmation UI // but *must* be called before registering any tasks var access = await BackgroundExecutionManager.RequestAccessAsync(); // A ‘good‘ status return on Phone is BackgroundAccess.AllowedMayUseActiveRealTimeConnectivity if (access == BackgroundAccessStatus.Denied) { // Either the user has explicitly denied background execution for this app // or the maximum number of background apps across the system has been reached // Display some informative message to the user... } BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder(); taskBuilder.Name = "MyBackgroundTask"; // Many different trigger types could be used here SystemTrigger trigger = new SystemTrigger(SystemTriggerType.TimeZoneChange, false); taskBuilder.SetTrigger(trigger); taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable)); // Entry point is the full name of our IBackgroundTask implementation // Good practice to use reflection as here to ensure correct name taskBuilder.TaskEntryPoint = typeof(MyBackgroundTask.TheTask).FullName; BackgroundTaskRegistration registration = taskBuilder.Register(); // Optionally, handle the progress/completed events of the task registration.Progress += registration_Progress; registration.Completed += registration_Completed; }
5、获取后台任务及取消注册后台任务,代码如下:
// AllTasks is a dictionary <Guid, IBackgroundTaskRegistration> so you can get back // to your registration by id or by posiiton, or select First if you only have one registration. var taskRegistration = BackgroundTaskRegistration.AllTasks.Values.FirstOrDefault(); // We could then unregister the task, optionally cancelling any running instance if (taskRegistration != null) { taskRegistration.Unregister(true); } // Release the progress/completed event subscriptions registration.Progress -= registration_Progress; registration.Completed -= registration_Completed;
tips:在Debugger 中我们可以这样触发后台任务,如图
标签:
原文地址:http://www.cnblogs.com/NEIL-X/p/4193175.html