views:

38

answers:

2

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];
        }
    }
}
A: 

It should be thread-safe, but why bother?

A "standard" singleton will also be accessible across the entire application, and it won't require injecting and keeping a reference to the HttpApplicationState:

public sealed class EmailWorker
{
    private EmailWorker() { }

    private static class NestedWorker
    {
        static NestedWorker() { }

        internal static readonly EmailWorker Instance = new EmailWorker();
    }

    public static EmailWorker Instance
    {
        get { return NestedWorker.Instance; }
    }
}
LukeH
A bit of clarification. I need to access it across all instances of the web application. The EmailWorker class is a thread that is started on the ApplicationStart event.
robbymurphy
@robby: But the `HttpApplicationState` is only per-application, exactly the same as a "standard" singleton would be.
LukeH
Is that because the instance is static?
robbymurphy
@robbymurphy: Yes.
SLaks
A: 

You don't need to use Application state at all.

SLaks