开发者

Thread safety of C# singleton instance in ApplicationState

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 EmailWo开发者_JAVA技巧rker {
    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];
        }
    }
}


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


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; }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜