# Thread Safety in Singleton Design Pattern using Lazy keyword
Lazy keyword provides support for lazy initialization. In order to make a property as lazy, we need to pass the type of object to the lazy keyword which is being lazily initialized.
By default, Lazy<T> objects are thread-safe. In multi-threaded scenarios, the first thread which tries to access the Value property of the lazy object will take care of thread safety when multiple threads are trying to access the Get Instance at the same time.
Therefore, it does not matter which thread initializes the object or if there are any thread race conditions that are trying to access this property.
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SingletonDemo
{
class Program
{
static void Main(string[] args)
{
Parallel.Invoke(
() => PrintStudentDetails(),
() => PrintEmployeeDetails()
);
Console.ReadLine();
}
private static void PrintEmployeeDetails()
{
Singleton fromEmployee = Singleton.GetInstance;
fromEmployee.PrintDetails("From Employee");
}
private static void PrintStudentDetails()
{
Singleton fromStudent = Singleton.GetInstance;
fromStudent.PrintDetails("From Student");
}
}
}
Singleton.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SingletonDemo
{
public sealed class Singleton
{
private static int counter = 0;
private Singleton()
{
counter++;
Console.WriteLine("Counter Value " + counter.ToString());
}
private static readonly Lazy<Singleton> instance =
new Lazy<Singleton>(()=>new Singleton());
public static Singleton GetInstance
{
get
{
return instance.Value;
}
}
public void PrintDetails(string message)
{
Console.WriteLine(message);
}
}
}
Tuesday, 8 March 2022
Thread Safety in Singleton Design Pattern using Lazy keyword
Subscribe to:
Post Comments (Atom)
Search This Blog
Creating your first "Alexa" Skill
Index What is Alexa What is Alexa Skill? Why is it required when Alexa already equipped with voice assistant? Dev...
About Me
Menu
-
Index What is Alexa What is Alexa Skill? Why is it required when Alexa already equipped with voice assistant? Dev...
-
Adding Azure AD B2C to React Native App Register your app in Azure active directory 1. Go to azure ad b2c, app registratio...
-
# Project file 1. .net Core project file no longer contains file or folder reference - all files and folder present within the root fol...
No comments:
Post a Comment