简体   繁体   中英

C# Singleton - Used by multiple clients

I've recently learned about the Singleton pattern, and I have a question about it:

Given the following singleton:

public class Singleton
{
    private static readonly Lazy<Singleton> lazyInstance =
        new Lazy<Singleton>(() => new Singleton(), true);

    private Singleton()
    {
        // Stuff that must only happen once.
        Console.WriteLine("Single ctor");
    }

    public static Singleton Instance => lazyInstance.Value;

    public static void DoSomething()
    {
        Console.WriteLine("Hello world!");
    }

    public string Name { get; set; }
}

and the following clients which live in the same assembly:

public class ClientA
{
    public ClientA
    {
        var instance = Singleton.Instance;
    }
}

public class ClientB
{
    public ClientB
    {
        var instance = Singleton.Instance;
    }
}

Will both clients end up using the same Singleton instance?

My real world example is much more complex, and there are some long running operations that would populate some properties in a singleton class during it's first instantiation, and I want to ensure that all clients using this singleton are using the same instance so that the long running operation would only run once.

NOTE: In my real world example, the client classes already derive from a base class which I have no control over.

new Lazy(() => new Singleton(), true) is only execute once. Instance always returns the same instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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