简体   繁体   English

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

[英]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. 我想知道是否将实例放在HttpApplicationState对象中是否仍然是线程安全的。 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? 我需要跨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];
        }
    }
}

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM