BNS error. The maximum number of ScheduledActions of this type have already been added.

In setting up a PeriodicTask in my Windows Phone 8 project, I ran into an error while debbugging: BNS error. The maximum number of ScheduledActions of this type have already been added. This occurs when there is already a PeriodicTask for the application and another one is added (only 1 PeriodicTask is allowed per application). To fix this, I found there are two solutions. The first (which I don’t like) is to find the PeriodicTask by the same name and remove it:

1

2

3

4

5

6

7

8

9

10

11

12

13

// initialize the periodic task

PeriodicTask myPeriodicTask=newPeriodicTask("TaskName");

myPeriodicTask.Description="Task Description";

myPeriodicTask.ExpirationTime=DateTime.Now.AddDays(10);

// find if there is a task by the same name and remove it

if(ScheduledActionService.Find(myPeriodicTask.Name)!=null)

{

ScheduledActionService.Remove(myPeriodicTask.Name);

}

// add the periodic task (throws exception)

ScheduledActionService.Add(myPeriodicTask);

A better implementation is to iterate through all PeriodicTasks for the application removing them: