Implementing The Singleton Pattern in C # [Reserved]

zhaozj2021-02-16  71

View Auther's Website

The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons do not allow any parameters to be specified when creating the instance -! as otherwise a second request for an instance but with a different parameter could be problematic (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate .) This article deals only with the situation where no parameters are required Typically a requirement of singletons is that they are created lazily -. ie that the instance is not created until it is first needed.

There are various different ways of implementing the singleton pattern in C #. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread- safe, simple and highly performant version. Note that in the code here, I omit the private modifier, as it is the default for class members. in many other languages ​​such as Java, there is a different default, and private should be used.

All these Implementations Share Four Common Characteristics, HoWever:

A single constructor, which is private and parameterless This prevents other classes from instantiating it (which would be a violation of the pattern) Note that it also prevents subclassing -.. If a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type is not known until runtime. The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more. A static variable which holds a reference to the single created instance, if any. A public static means of getting the reference to the single created instance , creating one if necessary. Note that all of these implementations also use a public static method GetInstance as the means of accessing the instance. In all cases, the method could easily be converted to a property with only an accessor, with no impact on thread-safety or performance.First version - not thread-safepublic sealed class Singleton {static Singleton instance = null; Singleton () {} public static Singleton GetInstance () {if (instance == null) instance = new Singleton ( Return Instance;}}

As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance == null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model does not guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.Second version - simple thread-safetypublic sealed class Singleton {static Singleton instance = null; static readonly object padlock = new object (); Singleton () {} public static Singleton GetInstance () {lock (padlock) {if (instance == null) instance = new Singleton (); Return instance;}}}

This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it, the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note that instead of locking on typeof (Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type ) risks performance issues and even deadlocks This is a general style preference of mine -. wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (eg for waiting / . pulsing a queue) Usually such objects should be private to the class they are used in This helps to make writing thread-safe applications significantly easier.Third version -. attempted thread-safety using double-check lockingpublic sealed class Singleton {static Singleton instance = NULL; Static Readonly Object Padlock = New Object (); Singleton () {} public static singleleton getinstance () {ix (instance == null) { Lock (Padlock) {if (instance == null) instance = new singleleton ();}} Return Instance;}}

This Implementation Attempts to Be Thread-Safe without The Necessity Of Taking Out A Lock Every. Unfortunately, There Are Four Dow Dowides To The Pattern:

It does not work in Java. This may seem an odd thing to comment on, but it's worth knowing if you ever need the singleton pattern in Java, and C # programmers may well also be Java programmers. The Java memory model does not ensure that the constructor completes before the reference to the new object is assigned to instance. The Java memory model is going through a reworking for version 1.5, but double-check locking is anticipated to still be broken after this. It almost certainly does not work in .NET either. Claims have been made that it does, but without any convincing evidence. Various people who are rather more trustworthy, however, such as Chris Brumme, have given convincing reasons why it does not. Given the other disadvantages, why take the risk? I believe it can be fixed by making the instance variable volatile, but that slows the pattern down more. (of course, correct but slow is better than incorrect but broken, but when speed was one of the reasons for using this Pattern in the first place, it looks even less attractive.) It can also be fixed using explicit memory barriers, but experts seem to find it hard to agree on just which memory barriers are required. I do not know about you, but when experts disagree about whether or not something should work, I try to avoid it entirely It's easy to get wrong The pattern needs to be pretty much exactly as above -... any significant changes are likely to impact either performance or correctness It still does not perform as Well as the latlementations. Fourth Version - Not Quite As Lazy, But Thread-Safe without Using Lockspublic Sealed Class Singleton {Static Readonly Singleton Instance = New Singleton ();

// Explicit static constructor to tell C # compiler // not to mark type as beforefieldinit static Singleton () {} Singleton () {} public static Singleton GetInstance () {return instance;}} As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it Well, static constructors in C # are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain Given?. . that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples There are a couple of wrinkles, however:

It's not as lazy as the other implementations. In particular, if you have static members other than GetInstance, the first reference to those members will involve creating the instance. This is corrected in the next implementation. There are complications if one static constructor invokes another which invokes the first again Look in the .NET specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type initializers -. they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle. The laziness of type initializers is only guaranteed by .NET when the type is not marked with a special flag called beforefieldinit. Unfortunately, the C # compiler (as provided in the .NET 1.1 runtime , at Least) Marks All Types Which Don't Have A Static Constructor (IE A Block Which Looks Like a Construction But Is Marked Static) AS Beforefieldinit. I Now Have A Discussion Page With more detai ls about this issue. Also note that it affects performance, as discussed near the bottom of this article.One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the method entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a method in case further action is needed in future, and JIT inlining is likely to make the performance identical. (Note that the static constructor itself Is Still Required if You Require Laziness.)

Fifth version - fully lazy instantiationpublic sealed class Singleton {Singleton () {} public static Singleton GetInstance () {return Nested.instance;} class Nested {// Explicit static constructor to tell C # compiler // not to mark type as beforefieldinit static Nested () {} internal static readonly Singleton instance = new Singleton ();}} Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in GetInstance This means the implementation is fully lazy, but. has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance to be internal here. that does not raise any other problems, though As the class itself is private. The code is a bit more completed in order Er to make the instantiation lazy, however.

转载请注明原文地址:https://www.9cbs.com/read-15948.html

New Post(0)