When you create a background agent for Windows Phone 7 there are a couple of important details you must be aware of:

  1. The total scheduled time for the agent to execute is 25 seconds, if you exceed it the agent will be killed by the scheduler.
  2. The max amount of memory available is 6 MB, if the agent allocates more the agent will be, again, killed.
  3. With Visual Studio debugger attached these limits are disabled.

An agent is killed silently and after two killing operations the scheduler will automatically disable it and your user probably will start wondering why your wonderful tile doesn’t work as expected.

The common problem I face when dealing with agents is that 6 MB of memory are a very strict constraint especially when you realize that the agent alone consumes more than 3 MB (in real cases I got more than 5 MB allocated at startup)
So what can you do do live in a such restrict space? along with optimizations (in some cases I ended up duplicating code in order to avoid to load some dependencies) my suggestion is: never trust the debugger, with it attached the allocated memory increases so you might end up with wrong measurements.
What I normally do is to write inside application tile what is the real amount of occupied memory so that I can quickly estimate how long I can go.

Code is really straightforward:

public class ScheduledAgent : ScheduledTaskAgent
{
protected override void OnInvoke(ScheduledTask task)
{
ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault();
if (tile != null)
{
var current = DeviceStatus.ApplicationCurrentMemoryUsage;

ShellTileData data = new StandardTileData
{
Title = "Occ:" + current.ToString(CultureInfo.InvariantCulture),
};

tile.Update(data);
}

NotifyComplete();
}
}
 
And here are the differences between debug and standalone mode:
 
image debugger attached
imageStandalone
 
Compared to overall 6MB, an important difference…

Thursday, March 15, 2012 7:24 PM