开发者

Thread safety of C# singleton instance in ApplicationState

开发者 https://www.devze.com 2023-01-20 21:49 出处:网络
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

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

精彩评论

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