Im trying to test my singleton object in C# but somehow not satisfied on how I brute force instantiating the object(using parallel foreach).
Is there a right way/better way to test it?
Im trying to test my singleton object in C# but somehow not satisfied on how I brute force instantiating the object(using parallel foreach).
Is there a right way/better way to test it?
I don't understand what you mean with "parallel foreach". A singleton is implemented like this:
public class MyClass
{
private static MyClass _instance;
private MyClass()
{
//Do Stuff
}
public static MyClass GetInstance()
{
if(_instance == null)
_instance = new MyClass();
return _instance;
}
}
Another way, instead of a Method is a Property:
private static readonly object LockObject = new object();
private static MyClass _instance;
public static MyClass Instance
{
get
{
lock (LockObject)
{
return _instance ?? (_instance = new MyClass());
}
}
}
While I prefer the first Method, cause it's much easier to implement, even for beginners, the Property is also a good way
Singleton class can have only one instance, If it is initialized multiple times then that means you have not correctly implemented the Singleton Design.
You can check the instance.Hashcode() value, it must remain same wherever you are using the instance of that Singleton class.