How can I save the settings in the IsolatedStorage while BackgroundAudioPlayer's instance is active?

前端 未结 1 1312
野趣味
野趣味 2021-01-17 04:51

I have Two projects in my Solution. Let\'s say Project A and Project B.

Project A

It\'s the main project and has settings. I have a check box to gi

相关标签:
1条回答
  • 2021-01-17 05:10

    I agree that Background Audio is a breast. Whenever using any background agent you cannot rely on the ApplicationSettings to be synced. If you want to have settings saved and accessed from the UI (app) and background (audio agent) you should save a file. You can serialize the settings using Json.Net and save a file to a known location. Here is sample of what is might look like

    // From background agent
    var settings = Settings.Load();
    if(settings.Foo)
    {
        // do something
    }
    

    And here is a sample Settings File. The settings would need to be saved on a regular basis.

    public class Settings
    {
        private const string FileName = "shared/settings.json";
    
        private Settings() { }
    
        public bool Foo { get; set; }
    
        public int Bar { get; set; }
    
        public static Settings Load()
        {
            var storage = IsolatedStorageFile.GetUserStoreForApplication();
            if (storage.FileExists(FileName) == false) return new Settings();
    
            using (var stream = storage.OpenFile(FileName, FileMode.Open, FileAccess.Read))
            {
                using (var reader = new StreamReader(stream))
                {
                    string json = reader.ReadToEnd();
                    if (string.IsNullOrEmpty(json) == false)
                    {
                        return JsonConvert.DeserializeObject<Settings>(json);
                    }
                }
            }
            return new Settings();
        }
    
        public void Save()
        {
            var storage = IsolatedStorageFile.GetUserStoreForApplication();
            if(storage.FileExists(FileName)) storage.DeleteFile(FileName);
            using (var fileStream = storage.CreateFile(FileName))
            {
                //Write the data
                using (var isoFileWriter = new StreamWriter(fileStream))
                {
                    var json = JsonConvert.SerializeObject(this);
                    isoFileWriter.WriteLine(json);
                }
            }
        }
    }
    

    I personally have a FileStorage class that I use for saving/loading data. I use it everywhere. Here it is (and it does use the Mutex to prevent access to the file from both background agent and app). You can find the FileStorage class here.

    0 讨论(0)
提交回复
热议问题