Last active
February 21, 2020 20:59
-
-
Save gucu112/ec1abf5f07d37afa95b9b2966f7ad513 to your computer and use it in GitHub Desktop.
C# Singleton Pattern
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
namespace Gucu112.SingletonPattern | |
{ | |
class Singleton : IDisposable | |
{ | |
private static Lazy<Singleton> instance | |
= new Lazy<Singleton>(() => new Singleton()); | |
private Singleton() | |
{ | |
// Singleton initialized | |
} | |
public static Singleton Instance => instance.Value; | |
public void Dispose() | |
{ | |
if (instance.IsValueCreated) | |
{ | |
// Singleton disposed | |
instance = new Lazy<Singleton>(() => new Singleton()); | |
} | |
} | |
} | |
} |
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
<Query Kind="Program" /> | |
void Main() | |
{ | |
"Calling singleton dispose".Dump(); | |
Singleton.Instance.Dispose(); | |
"Calling singleton instance in using clause".Dump(); | |
using (var singleton = Singleton.Instance) | |
{ | |
"Using singleton instance".Dump(); | |
} | |
"Calling singleton instance".Dump(); | |
var test = Singleton.Instance; | |
"Calling singleton dispose".Dump(); | |
Singleton.Instance.Dispose(); | |
"Calling singleton dispose".Dump(); | |
Singleton.Instance.Dispose(); | |
} | |
public class Singleton : IDisposable | |
{ | |
private static Lazy<Singleton> instance | |
= new Lazy<Singleton>(() => new Singleton()); | |
private Singleton() | |
{ | |
"Singleton initialized".Dump(); | |
} | |
public static Singleton Instance => instance.Value; | |
public void Dispose() | |
{ | |
if (instance.IsValueCreated) | |
{ | |
"Singleton disposed".Dump(); | |
instance = new Lazy<Singleton>(() => new Singleton()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment