I post this specific question after the other one I wasn’t able to solve.
Briefly: even if I create a static class (with static vars and/or properties), main app and background agent don’t use the same static class, but both create a new instance of it; so it’s impossible to share data between these projects!!
To test it:
- Create a new Windows Phone application (called AppTest)
- Add a ScheduledTask project (called Agent)
- In AppTest put a reference to project Agent
- Create a new Windows Phone Library project (called Shared)
- Both in AppTest and Agent put a reference to project Shared
Then use this basic test code.
AppTest
private readonly string taskName = "mytest";
PeriodicTask periodicTask = null;
public MainPage()
{
InitializeComponent();
Vars.Apps.Add("pluto");
Vars.Order = 5;
StartAgent();
}
private void RemoveTask()
{
try
{
ScheduledActionService.Remove(taskName);
}
catch (Exception)
{
}
}
private void StartAgent()
{
periodicTask = ScheduledActionService.Find(taskName) as PeriodicTask;
if (periodicTask != null)
RemoveTask();
periodicTask = new PeriodicTask(taskName)
{
Description = "test",
ExpirationTime = DateTime.Now.AddDays(14)
};
try
{
ScheduledActionService.Add(periodicTask);
ScheduledActionService.LaunchForTest(taskName,
TimeSpan.FromSeconds(10));
}
catch (InvalidOperationException exception)
{
}
catch (SchedulerServiceException)
{
}
}
Agent
protected override void OnInvoke(ScheduledTask task)
{
if (Vars.Apps.Count > 0)
Vars.Order = 1;
NotifyComplete();
}
Shared
public static class Vars
{
public static List<string> Apps = null;
public static int Order;
static Vars()
{
Apps = new List<string>();
Order = -1;
}
}
When you debug main app you can see that static constructor for static class is invoked (this is correct), but when agent is invoked Vars is not “used” but constructor is invoked another time, so creating a different instance.
Why? How can I share data between main app and background agent?
I’ve already tried to put Vars class in agent class and namespace, but the behaviour is the same.
Values of static variables are ‘instanced’ per loaded App Domain, which is a ‘subset’ of your running process. So static variables have different values per AppDomain, and therefore also per running process.
If you have to share data between processes, you need either to store it somewhere (e.g. a database), or you need to setup some communication between the processes (e.g. MSMQ or WCF).
Hope this helps.