2013-02-20 162 views
3

我想弄清楚为什么backgroundtask不会启动,但我不知道我做错了什么。后台任务不启动

我在做什么:我想要一个自动后台任务,它将通过WebApi下载最新的5个项目(数据是几KB)。下载后,它会检查本地文件,看看是否有新的项目可用。如果是这样,我想用新项目的数量在LiveTile上创建一个徽章。

我有以下代码:

private BackgroundTaskRegistration ScheduleBackgroundTask() 
{ 
    foreach (var cur in BackgroundTaskRegistration.AllTasks) 
    { 
     if (cur.Value.Name == "TimeTriggeredTask") 
     { 
      return (BackgroundTaskRegistration)(cur.Value); 
     } 
    } 

    var builder = new BackgroundTaskBuilder(); 

    builder.Name = "TimeTriggeredTask"; 
    builder.TaskEntryPoint = "Tasks.UpdateItemTask"; 
    builder.SetTrigger(new MaintenanceTrigger(15, false)); 
    builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable)); 
    builder.AddCondition(new SystemCondition(SystemConditionType.UserNotPresent)); 

    BackgroundTaskRegistration task = builder.Register(); 
    return task; 
} 

而且我的工作看起来是这样的:

namespace Tasks 
{ 
    public sealed class UpdateItemTask : IBackgroundTask 
    { 
     public async void Run(IBackgroundTaskInstance taskInstance) 
     { 
      Debug.WriteLine("Starting"); 

      BackgroundTaskDeferral _deferral = taskInstance.GetDeferral(); 

      DataHandler dataHandler = new DataHandler(); 
      BindableCollection<GeekAndPokeItemViewModel> latestItemsOnline = await dataHandler.GetData("10"); 
      BindableCollection<GeekAndPokeItemViewModel> latestItemsLocal = await dataHandler.GetLocalData(); 

      int difference = latestItemsOnline.Except(latestItemsLocal).Count(); 

      if (difference > 0) 
      { 
       BadgeUpdateManager.CreateBadgeUpdaterForApplication().Clear(); 
       BadgeNumericNotificationContent badgeContent = new BadgeNumericNotificationContent((uint)difference); 

       // send the notification to the app's application tile 
       BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badgeContent.CreateNotification()); 
      } 

      _deferral.Complete(); 
     } 
    } 
} 

在我appmanifest的backgroundTask扩展与任务“计时器”,并以正确的入口点。

所有代码在1个项目中。

即使连接(调试程序不启动应用程序,以及力来触发任务)的调试器,它不会打我的任务(或断点),并在事件查看器它给出的结果是:

带入口点Tasks.UpdateItemTask和名称TimeTriggeredTask的后台任务未能激活,错误代码为0x80010008。

我一直在检查The samples of MS background Tasks,但即使这些都没有帮助。我会建议这并不难,但我无法得到它的工作。

+0

也许只是在你的任务中的日志消息,看看它是否找不到它。 – Dreamwalker 2013-02-20 08:14:50

+0

调试器运行时没有问题,只有它不会在任务开始时触发断点,这意味着任务甚至没有被解雇......我想说,登录任务将不会有所帮助,因为任务根本不执行... – 2013-02-20 09:07:47

+0

我刚刚阅读了关于维护触发器类别的[文档](http://www.microsoft.com/en-us/download/details.aspx?id=27411) 。这个触发器实际上是一个SystemTrigger而不是一个TimeTrigger(在我的appmanifest中定义)。我改变了这一点,但仍然没有结果。我仍然有相同的错误信息... – 2013-02-20 10:11:34

回答

6

我终于搞定了!

第一:我已经将任务移动到一个新的程序集中作为Windows RT组件类型,并在我的WinRT应用程序中添加了一个引用。

第二:我有1 cs文件中的BackgroundTaskRegistration和UpdateItemTask,只有任务是密封的。我需要将BackgroundTaskRegistration也设置为密封,才能编译。一旦我强制触发触发器,它终于击中断点......