In this article, We are going to discuss the Lazy vs Eager loading in Singleton Design Pattern to Achieve Thread Safety in C# with a real-time example. Please read our previous content/article before proceeding to this article where we discussed the Thread Safe Singleton Design Pattern in C# with real-time examples. As part of this content, we are going to discuss the following main points.
- What is Non-Lazy or Eager Initialization
- Understanding The C# Lazy Keyword
- Lazy or Deferred Loading Initialization?
- How to make the singleton instance thread-safe using both Eager loading and Lazy loading with Examples?
What is Non-Lazy or Eager Initialization
using System; using System.Threading.Tasks; namespace ConsolePractice { public sealed class Singleton_Design_Pattern { private static int count =0; private static Singleton_Design_Pattern singletonInstance = null; private static readonly object objctlock = new object(); public static Singleton_Design_Pattern GetNewInstance { get { lock (objctlock) { if (singletonInstance == null) { singletonInstance = new Singleton_Design_Pattern(); }
} return singletonInstance; } }
private Singleton_Design_Pattern() { count++; Console.WriteLine("object "+count); } public void getEmployee(string message) { Console.WriteLine(message); } } } |
---|
using System; using System.Threading.Tasks;
namespace ConsolePractice {
public sealed class Singleton_Design_Pattern
{
private static int count =0;
private static readonly Singleton_Design_Pattern singletonInstance = new Singleton_Design_Pattern(); public static Singleton_Design_Pattern GetNewInstance
{ get {
return singletonInstance; }
}
private
Singleton_Design_Pattern()
{ count++; Console.WriteLine("object "+count);
}
public void getEmployee(string message)
{ Console.WriteLine(message);
}
} } |
---|
What are Lazy or Deferred Loading Initialization and Lazy keyword?
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace ConsolePractice {
public sealed class Singleton_Design_Pattern
{
private static int count =0;
private static readonly Lazy<Singleton_Design_Pattern> singletonInstance = new Lazy<Singleton_Design_Pattern>(()=>new Singleton_Design_Pattern()); public static Singleton_Design_Pattern GetNewInstance
{ get
{
return singletonInstance.Value; }
}
private
Singleton_Design_Pattern()
{ count++; Console.WriteLine("object "+count);
}
public void getEmployee(string message)
{ Console.WriteLine(message);
}
} } |
---|
Post a Comment (0)