ApplicationState中C#单例实例的线程安全性

时间:2010-10-20 22:39:03

标签: c# singleton thread-safety

我有一些代码,我一直在尝试检查线程安全性。我正在使用找到here的基本懒惰单例模型。如果我将实例放在HttpApplicationState对象中,我想知道它是否仍然是线程安全的。我需要在Web应用程序的所有实例中访问此实例,因此如果这不是线程安全的,我怎样才能使其线程安全?


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

2 个答案:

答案 0 :(得分:1)

您根本不需要使用应用程序状态。

答案 1 :(得分:0)

它应该是线程安全的,但为什么要这么麻烦?

整个应用程序也可以访问“标准”单例,并且不需要注入并保留对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; }
    }
}