Search code examples
c#windows-phone-8staticportable-class-libraryclass-library

How to persist data in a static variable when shared across library?


I have a main application (Windows Phone to be precise ). And its referencing another class library I have created. I have created a static variable in this class library and am changing those variables from the main application. The variable value is shown correctly when accessed from the main application but when i access the same variable from the class library itself then its showing a different value. Below is my code.

A class in My class library:

public class PlayerQueue
    {
        public static bool LoopStatus;

        public static PlayerQueueTrack GetNextSong(String audioTrackId)
        {
            if (LoopStatus)
                return audioTracks[audioTrackId];
        }
    }

Tap Method in my Windows Phone application:

 private void loopButton_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
    {
        PlayerQueue.LoopStatus = true;
    }

After my tap method is executed in phone application, if the GetNextSong() method is called from within the class library then the LoopStatus is shown as false even though it was set as true.

So the value in PlayerQueue.LoopStatus when accessed from Windows phone application is different and PlayerQueue.LoopStatus when accessed from a class library which contains the PlayerQueue.LoopStatus is giving a different value.

Can anyone please tell me how i can persist the data across the library and the application ?

EDIT: Adding the class in the class library from which am making the GetNextSong() call

public class AudioPlayer : AudioPlayerAgent
{
    private static volatile bool _classInitialized;

public AudioPlayer()
{
    if (!_classInitialized)
    {
        _classInitialized = true;
        // Subscribe to the managed exception handler
        Deployment.Current.Dispatcher.BeginInvoke(delegate
        {
            Application.Current.UnhandledException += AudioPlayer_UnhandledException;
        });
    }
}

protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState)
{
    PlayerQueueTrack playerTrack = PlayerQueue.GetNextSong(id);
}

}


Solution

  • Static values are persisted across an application domain. As long as your application is running and didn't create a new appdomain it will remain the same. Or another piece of code is changing it.

    Windows Phone 8 is a bit more complex because event tiles and the application tend to run in different app domains:

    Static variable value different in background agent

    If you have a static value across event tiles and background processes your last remaining option is to store it to a persistent data store / isolated storage.