Created
July 18, 2016 18:32
-
-
Save acazsouza/01af80995ebfa93efa2abb8c9dd2dc09 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//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; | |
} | |
} | |
} |
This file contains hidden or 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
//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; | |
} | |
} |
This file contains hidden or 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
//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