Created
July 30, 2013 20:15
-
-
Save dasjestyr/6116502 to your computer and use it in GitHub Desktop.
A thread-safe singleton example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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