I'm currently developping a "Singleton" class, but it has to withstand thread safety as I'm not only accessing, but also settings some stuff.. I was wondering how I could to this - as it seems the locking of stuff with lock(object)
feels somewhat hacky when I don't know what it's actually doing and if I have to make every single method thread safe as well?
So far I have this non thread safe code - as in each thread should access the same data. How would I best go about making it thread safe and keep it a singleton?
public class AppSession() {
private static AppSession _instance = new AppSession();
public static AppSession Instance { get { return _instance; } }
private AppSession() { }
private string _actionName = "none";
private DateTime? _actionTime = null;
public void ActionExecuted(string action) {
_actionName = action ?? String.Empty;
_actionTime = DateTime.UtcNow;
}
public LastAction {
get { return $"{_action} at {_actionTime?.Value.ToString()}"; }
}
}