I implemented Background Agents using this link. I register background agents in Application_Closing event inside app.xaml

private void Application_Closing(object sender, ClosingEventArgs e)
{
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem((object obj) =>
{
StartResourceIntensiveAgent();
StartPeriodicAgent();
autoResetEvent.Set();
});
autoResetEvent.WaitOne();
}
and remove background agents on Application_Launching event

private void Application_Launching(object sender, LaunchingEventArgs e)
{
ThreadPool.QueueUserWorkItem((object obj) =>
{
RemoveResourceIntensiveAgent();
RemovePeriodicAgent();
});
}
my implementation for start and end stubs

static PeriodicTask periodicTask;
static ResourceIntensiveTask resourceIntensiveTask;

public static PeriodicTask StartPeriodicAgent()
{
// Obtain a reference to the period task, if one exists
periodicTask = ScheduledActionService.Find(Constants.periodicTaskName) as PeriodicTask;

// If the task already exists and background agents are enabled for the
// application, remove the task and then add it again to update
// the schedule
if (periodicTask != null)
{
RemovePeriodicAgent();
}

periodicTask = new PeriodicTask(Constants.periodicTaskName);

// The description is required for periodic agents. This is the string that the user
// will see in the background services Settings page on the device.
periodicTask.Description = "a periodic task.";

// Place the call to Add in a try block in case the user has disabled agents.
try
{
ScheduledActionService.Add(periodicTask);
}
catch (Exception exception)
{
periodicTask = null;
throw exception;
}
return periodicTask;
}

public static void RemovePeriodicAgent()
{
try
{
periodicTask = ScheduledActionService.Find(Constants.periodicTaskName) as PeriodicTask;

if (periodicTask != null)
{
ScheduledActionService.Remove(Constants.periodicTaskName);
periodicTask = null;
}
}
catch (Exception e)
{
throw e;
}
}
Similar thing goes for ResourceIntensiveAgent.
inside my ScheduledAgent class i put a debug statement.

protected override void OnInvoke(ScheduledTask task)
{
Debug.WriteLine("Came in to schedule task at " + DateTime.Now.ToLocalTime());
NotifyComplete();
}
Now i run the application in debug mode and exit it, i can see my apps name in settings-> background tasks with "allowed" marked on it in red.
I leave this debbuging state for 2 hours and when i come back i can not see anything in the debug log. But the same thing works when i put

#if(DEBUG_AGENT)
ScheduledActionService.LaunchForTest(Constants.periodicTaskName, TimeSpan.FromSeconds(10));
#endif
in StartPeriodicAgent method.


Tried lot of things with it but could not succeed. Came across this and this but no good answer present out there.
Am i doing it wrong or PeriodicAgents are not behaving as they should.

Regards