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 itselfto be created,and usually gives simple access to that instance. Most commonly,singletons don't allow any parameters to be specifIEd when creating the instance -as otherwise a second request for an instance but with a different parameter Couldbe problematic! (If the same instance should be accessed for all requests with thesame parameter,the factory pattern is more appropriate.) This article deals only withthe situation where no parameters are required. Typically a requirement of singletonsis that they are created lazily - i.e. that the instance isn't created until it isfirst needed.
There are varIoUs different ways of implementing the singleton pattern in C#. I shallpresent 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,simpleand 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,thereis 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 isn't 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 property Instance
as the means of accessing the instance. In all cases,the property Could easily be convertedto a method,with no impact on thread-safety or performance.
// Bad code! Do not use! |
As hinted at before,the above is not thread-safe. Two different threads Could bothhave evaluated the test if (instance==null)
and found it to be true,then both create instances,which violates the singleton pattern. Note that in factthe instance may already have been created before the Expression is evaluated,butthe memory model doesn't guarantee that the new value of instance will be seen byother threads unless suitable memory barrIErs have been passed.
public sealed class Singleton |
This implementation is thread-safe. The thread takes out a lock on a sharedobject,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 thatall reads occur logically after the lock acquire,and unlocking makes sure that all writes occurlogically 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 threadenters 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 thisimplementation 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) risksperformance issues and even deadlocks. This is a general style preference of mine - whereverpossible,only lock on objects specifically created for the purpose of locking,or whichdocument that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue).Usually such objects should be private to the class they are used in. This helps to makewriting thread-safe applications significantly easIEr.
// Bad code! Do not use! |
This implementation attempts to be thread-safe without the necessity of taking out a lock every time.Unfortunately,there are four downsIDes to the pattern:
It doesn't 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 doesn't ensure that the constructor completes before the reference to the new object is assigned to instance. The Java memory model underwent a reworking for version 1.5,but double-check locking is still broken after this without a volatile variable (as in C#). Without any memory barrIErs,it's broken in the ECMA Cli specification too. It's possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec) it's safe,but I'd rather not rely on those stronger semantics,especially if there's any doubt as to the safety. Making theinstance
variable volatile can make it work,as would explicit memory barrIEr calls,although in the latter case even experts can't agree exactly which barrIErs are required. I tend to try to avoID situations where experts don't agree what's right and what's wrong! 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 doesn't perform as well as the later implementations. Fourth version - not quite as lazy,but thread-safe without using locks public sealed class Singleton |
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 iscreated or a static member is referenced,and to execute only once per AppDomain. Given thatthis check for the type being newly constructed needs to be executed whatever else happens,itwill be faster than adding extra checking as in the prevIoUs examples. There are a couple ofwrinkles,however:
It's not as lazy as the other implementations. In particular,if you have static members other thanInstance
,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 isn't 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 (i.e. a block which looks like a constructor but is marked static) as beforefIEldinit
. I Now have a discussion page with more details 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 makeinstance
a public static Readonly variable,and get rID of the property entirely.This makes the basic skeleton code absolutely tiny! Many people,however,prefer to have aproperty in case further action is needed in future,and JIT inlining is likely to makethe performance IDentical. (Note that the static constructor itself is still requiredif you require laziness.)
public sealed class Singleton |
Here,instantiation is triggered by the first reference to the static member of the nestedclass,which only occurs in Instance
. This means the implementation is fullylazy,but has all the performance benefits of the prevIoUs ones. Note that although nestedclasses have access to the enclosing class's private members,the reverse is not true,hencethe need for instance
to be internal here. That doesn't raise any other problems,though,as the class itself is private. The code is a bit more complicated in order to makethe instantiation lazy,however.
In many cases,you won't actually require full laziness - unless your class initializationdoes something particularly time-consuming,or has some sIDe-effect elsewhere,it's probablyfine to leave out the explicit static constructor shown above. This can increase performanceas it allows the JIT compiler to make a single check (for instance at the start of a method)to ensure that the type has been initialized,and then assume it from then on. If yoursingleton instance is referenced within a relatively tight loop,this can make a (relatively)significant performance difference. You should decIDe whether or not fully lazy instantiationis required,and document this decision appropriately within the class. (See below for more onperformance,however.)
ExceptionsSometimes,you need to do work in a singleton constructor which may throw an exception,butmight not be fatal to the whole application. Potentially,your application may be able tofix the problem and want to try again. Using type initializers to construct the singletonbecomes problematic at this stage. Different runtimes handle this case differently,but I don't kNow of any which do the desired thing (running the type initializer again),andeven if one dID,your code would be broken on other runtimes. To avoID these problems,I'dsuggest using the second pattern Listed on the page - just use a simple lock,and go throughthe check each time,building the instance in the method/property if it hasn't already beensuccessfully built.
Thanks to Andriy Tereshchenko for raising this issue.
A word on performanceA lot of the reason for this page stemmed from people trying to be cLever,and thus comingup with the double-checked locking algorithm. There is an attitude of locking being expensivewhich is common and misguIDed. I've written a very quick benchmarkwhich just acquires singleton instances in a loop a billion ways,trying different variants.It's not terribly scIEntific,because in real life you may want to kNow how fast it is if eachiteration actually involved a call into a method fetching the singleton,etc. However,it doesshow an important point. On my laptop,the slowest solution (by a factor of about 5) is the lockingone (solution 2). Is that important? Probably not,when you bear in mind that it still managed toacquire the singleton a billion times in under 40 seconds. That means that if you're "only"acquiring the singleton four hundred thousand times per second,the cost of the acquisitionis going to be 1% of the performance - so improving it isn't going to do a lot. Now,if you areacquiring the singleton that often - isn't it likely you're using it within a loop? If you carethat much about improving the performance a little bit,why not declare a local variable outsIDe the loop,acquire the singleton once and then loop. Bingo,even the slowest implementation becomes easilyadequate.
I would be very interested to see a real world application where the difference between usingsimple locking and using one of the faster solutions actually made a significant performance difference.
Conclusion (modifIEd slightly on January 7th 2006)There are varIoUs different ways of implementing the singleton pattern in C#.A reader has written to me detailing a way he has encapsulated the synchronization aspect,which while I ackNowledge may be useful in a few very particular situations(specifically where you want very high performance,and the ability to determine whether or notthe singleton has been created,and full laziness regardless of other staticmembers being called). I don't personally see that situation coming up often enoughto merit going further with on this page,but please mailme if you're in that situation.
My personal preference is for solution 4: the only time I would normally go away from itis if I needed to be able to call other static methods without triggering initialization,orif I needed to kNow whether or not the singleton has already been instantiated. I don't rememberthe last time I was in that situation,assuming I even have. In that case,I'd probably gofor solution 2,which is still nice and easy to get right.
Solution 5 is elegant,but trickIEr than 2 or 4,and as I saID above,the benefits it provIDesseem to only be rarely useful.
(I wouldn't use solution 1 because it's broken,and I wouldn't use solution 3 because it has nobenefits over 5.)
总结
以上是内存溢出为你收集整理的Implementing the Singleton Pattern in C#全部内容,希望文章能够帮你解决Implementing the Singleton Pattern in C#所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)