What is the best way to implement a Singleton Design Pattern in C # with performance limits?

Please let me know what is the best way to implement a Singleton Design Pattern in C # with performance limitations?

+6
design-patterns
source share
5 answers
+4
source share

One of the best article on Signleton jon skeet template.

http://www.yoda.arachsys.com/csharp/singleton.html

+3
source share
public class Singleton { static readonly Singleton _instance = new Singleton(); static Singleton() { } private Singleton() { } static public Singleton Instance { get { return _instance; } } } 
+2
source share

Paraphrase from C # in depth : There are various ways to implement a singleton pattern in C #, starting with Unsafe for a fully lazily loaded, thread safe, simple and highly efficient version.

The best version is using .NET 4 Lazy type:

 public sealed class Singleton { private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton()); public static Singleton Instance { get { return lazy.Value; } } private Singleton() { } } 

It just works well. It also allows you to check if an instance with IsValueCreated has yet been created if you need it.

+2
source share

Only recently did I find out that Singleton is considered by many to be an anti-pattern and should be avoided. A cleaner solution might be to use DI or other functions. Even if you go with a singleton, just read this interesting discussion What is so bad about singles?

+1
source share

All Articles