Created
February 7, 2017 16:32
-
-
Save martinsuchan/9f31502a03cab5120c10c1b161eef33e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using Windows.Storage; | |
namespace TinyCore.Storage | |
{ | |
public abstract class SettingBase | |
{ | |
/// <summary> | |
/// Access to LocalSettings must be atomic. | |
/// </summary> | |
protected static readonly object SettingsLock = new object(); | |
/// <summary> | |
/// Keep only one shared instance of LocalSettings. | |
/// </summary> | |
protected static readonly ApplicationDataContainer Local = ApplicationData.Current.LocalSettings; | |
} | |
/// <summary> | |
/// Encapsulates a key/value pair stored in Application Settings. | |
/// Note limit for each object is about 4kB of data! | |
/// </summary> | |
/// <typeparam name="T">Type to store, must be serializable.</typeparam> | |
public class Setting<T> : SettingBase | |
{ | |
private readonly string name; | |
private T value; | |
private readonly T defaultValue; | |
private bool hasValue; | |
public Setting(string name) | |
: this(name, default(T)) {} | |
public Setting(string name, T defaultValue) | |
{ | |
this.name = name; | |
this.defaultValue = defaultValue; | |
} | |
public T Value | |
{ | |
get | |
{ | |
lock (SettingsLock) | |
{ | |
// Check for the cached value | |
if (hasValue) return value; | |
try | |
{ | |
object rawValue; | |
// Try to get the value from Application Settings | |
if (Local.Values.TryGetValue(name, out rawValue)) | |
{ | |
value = (T)rawValue; | |
} | |
else | |
{ | |
// It hasn’t been set yet | |
value = defaultValue; | |
Local.Values[name] = defaultValue; | |
} | |
} | |
catch (Exception e) | |
{ | |
Debug.WriteLine("Setting Get error, name: {0}, {1}", name, e); | |
value = defaultValue; | |
Local.Values[name] = defaultValue; | |
} | |
hasValue = true; | |
return value; | |
} | |
} | |
set | |
{ | |
lock (SettingsLock) | |
{ | |
// Save the value to Application Settings | |
Local.Values[name] = value; | |
this.value = value; | |
hasValue = true; | |
} | |
} | |
} | |
/// <summary> | |
/// The default value of the object. | |
/// </summary> | |
public T DefaultValue => defaultValue; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment