Singleton Design Pattern ensures that Only One Instance is created. But, It will impose challenges in the Multi-threaded scenarios.
- Multiple Thread causes Issues If entering the GetInstance() method
- We need to use Lock keyword to ensure only 1 Thread enters the Instance Creation
- We need to add additional check on Instance is Null inside the lock statement
public class ConnectionPool
{
private static ConnectionPool instance;
private static object _lockObject = new object();
public static ConnectionPool GetInstance()
{
if (instance == null)
{
lock (_lockObject)
{
if (instance != null)
instance = new ConnectionPool();
}
}
return instance;
}
private ConnectionPool()
{
// doesn’t matter what’s here
}
}
Reference
I have written a book Design Patterns in C# few years back.