Table of contents (for linking purposes...)
- Introduction
- Non-thread-safe version
- Simple thread safety via locking
- Double-checked locking
- Safety through initialization
- Safe and fully lazy static initialization
Lazy
- Exceptions
- Performance
- Conclusion
Sixth version - using .NET 4's Lazy
type
If you're using .NET 4 (or higher), you can use the System.Lazy type to make the laziness really simple. All you need to do is pass a delegate to the constructor which calls the Singleton constructor - which is done most easily with a lambda expression.
public sealed class Singleton
{
private static readonly Lazy lazy =
new Lazy(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
{
private static readonly Lazy
new Lazy
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
It's simple and performs well. It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that.
No comments:
Post a Comment