Skip to content

Instantly share code, notes, and snippets.

@dasjestyr
Created July 30, 2013 20:15
Show Gist options
  • Save dasjestyr/6116502 to your computer and use it in GitHub Desktop.
Save dasjestyr/6116502 to your computer and use it in GitHub Desktop.
A thread-safe singleton example
void Main()
{
var inst1 = Employee.Instance;
Console.WriteLine(Employee.Count); //1
Console.WriteLine(Employee.Count); //1
var inst2 = Employee.Instance;
Console.WriteLine(Employee.Count); //2
Console.WriteLine(Employee.Count); //2
}
public class Employee
{
public static int Count;
private static readonly object threadLock = new object();
private static Employee _instance;
public static Employee Instance
{
get
{
lock(threadLock)
{
if(_instance == null)
{
_instance = new Employee();
}
Count++;
return _instance;
}
}
}
static Employee()
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment