Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#
Print

Simple Singleton Pattern in C#

4.00/5 (4 votes)
30 Oct 2011CPOL 10.7K  
The problem with alternative 3 and 4 is that it is not multi-threaded.Two threads may check for null, then the two will create the new instance. The race condition only happens at the first accesses. If a single thread accesses the object, then later many threads do the access, there is no...
The problem with alternative 3 and 4 is that it is not multi-threaded.
Two threads may check for null, then the two will create the new instance. The race condition only happens at the first accesses. If a single thread accesses the object, then later many threads do the access, there is no problem, so it is hard to cause that bug... but it is hard to discover it later.

EDIT: Sorry. Alternative 3 works well in multi-threaded environments, as it is reading a read-only field that's set during initialization. When I saw it, I got the impression the property was initializing it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)