This article going to explain on thread-safe singleton design pattern by using parallel.invoke the method in the main class and the object class and lock class in the singleton class.
parallel.invoke is used to invokes methods as action. and pass the methods in parallel.invoke.
actually, we can achieve the singleton design pattern without parallel class or lock class inside the singleton design pattern but the problem is the thread-safe. if we don't take care of thread-safe then there is no use if we implement the singleton. for example, parallel to get multi-thread concept.
Lazy initialization works well in a single-threaded scenario. but not the well multi-threaded scenario.
Main Class :
Parallel.Invoke(
()=> Customer(),
()=> Vendor()
);
using System; using System.Threading.Tasks;
namespace ConsolePractice {
class Program
{
static void Main(string[] args)
{ Parallel.Invoke( ()=> Customer(), ()=> Vendor() ); Console.ReadLine();
}
private static void Vendor()
{ Singleton_Design_Pattern obj1 = Singleton_Design_Pattern.GetNewInstance; obj1.getEmployee("Vendor Name
Tata");
} private static Singleton_Design_Pattern Customer()
{ Singleton_Design_Pattern obj = Singleton_Design_Pattern.GetNewInstance; obj.getEmployee("Employee Name
Murali Krishna"); return obj;
}
} } |
---|
Thread Safe Singleton design pattern.
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);
}
} } |
---|
OutPut Thread Safe Singleton Design Pattern in C#
Double checked locking approach for Thread-safe Singleton Design Pattern in C#
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 {
if (singletonInstance == null) { 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); } } } |
---|
Post a Comment (0)