I have a bit of code that I've been trying to examine for thread safety. I'm using the basic lazy singleton model found here. I was wondering if it is still thread safe if I'm putting the instance in the HttpApplicationState object. I need to access this instance across all instances of the web application, so if this is not thread safe how can I make it thread safe?
public sealed class EmailWorker {
private HttpApplicationState _app;
private const EMAIL_WORKER = "EmailWorker";
EmailWorker() { }
class NestedWorker {
static NestedWorker() { }
internal static readonly EmailWorker Instance = new EmailWorker();
}
public static void Initialize(HttpApplicationState appState) {
_appState = appState;
_appState.Lock();
if (_appState[EMAIL_WORKER] == null) {
_appState.Add(EMAIL_WORKER, NestedWorker.Instance);
}
_appState.UnLock();
}
public static EmailWorker Instance {
get {
// TODO: If we haven't called Initialize() first then throw exception
return (EmailWorker)_appState[EMAIL_WORKER];
}
}
}