Skip to content

Instantly share code, notes, and snippets.

@acazsouza
Created July 18, 2016 18:32
Show Gist options
  • Save acazsouza/01af80995ebfa93efa2abb8c9dd2dc09 to your computer and use it in GitHub Desktop.
Save acazsouza/01af80995ebfa93efa2abb8c9dd2dc09 to your computer and use it in GitHub Desktop.
//thread-safe
public class MySingleton
{
private static readonly Lazy<MySingleton> _mySingleton = new Lazy<MySingleton>(() => new MySingleton());
private MySingleton() { }
public static MySingleton Instance
{
get
{
return _mySingleton.Value;
}
}
}
//thread-safe
public class MySingleton {
private static object myLock = new object();
private static volatile MySingleton mySingleton = null;
private MySingleton() {
}
public static MySingleton GetInstance() {
if (mySingleton == null) {
lock (myLock) {
if (mySingleton == null) {
mySingleton = new MySingleton();
}
}
}
return mySingleton;
}
}
//non thread-safe
public class MySingleton {
private static object myLock = new object();
private static MySingleton mySingleton = null;
private MySingleton() {
}
public static MySingleton GetInstance() {
if (mySingleton == null) {
lock (myLock) {
mySingleton = new MySingleton();
}
}
return mySingleton;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment