Search code examples
c#windows-runtimewindows-store-appsuwpwinrt-component

Null static value from class inside WinRT background task


I'm trying to save configuration(json string) passed from WinJs and read this configuration inside backgroundTask. I'm declaring static variable so I can read values from background Task but it returns null.

Class to store configuration:

public sealed class BackgroundTaskConfiguration
{
    internal static string jsonString;

    public static IList<Config> TileConfig { get; set; }

    public static void SaveTileConfig(string jsonConfig) {

        TileConfig = new List<Config>();
        jsonString = jsonConfig;

        JsonArray jsonArray;
        if (JsonArray.TryParse(jsonConfig, out jsonArray))
        {
            foreach (var item in jsonArray)
            {
                TileConfig.Add(Config.Create(item.GetObject()));
            }
        }
    }

    public static IList<Config> GetConfig() {
        return TileConfig;
    }
}

Then, I'm simply reading inside BackgroundTask method like

 var confg = BackgroundTaskConfiguration.TileConfig;

Or

var confg = BackgroundTaskConfiguration.GetConfig();

Both the lines returns null. Any clue what is not correct here? Thanks


Solution

  • I guess you're calling SaveTileConfig in your front end, and expect the static value to be available in the background task automatically?

    That's unfortunately not how it works. See background tasks and main app as different programs which run in different contexts. They only have in common that they run on the same device and in the same folder.

    The solution is to serialize and save your TileConfig in some file and then load and deserialize it in the background task. There's no other way to share data between bg task + foreground app.