I have a singleton class where a list of objects is placed. So I have a class that sets items to that list. Then, I have another class that gets the list of objects from that singleton class. My issue is when I receive an nservicebus message and get the list from the singleton class, there are times that the list does not contain any objects. And there are times that the objects exist. So, what I did is every time I get the singleton instance I execute 'GetHashCode' and confirmed that there are 2 different instances of the Singleton class. What did I implement incorrectly with my code?
public class SingletonClass
{
private static readonly object _lockObj = new object();
private static readonly object _lockObjList = new object();
static SingletonClass _singletonClass;
private static List<object> _objList;
private SingletonClass()
{
}
public static SingletonClass Instance
{
get
{
lock(_lockObj)
{
if (null == _singletonClass)
{
_singletonClass= new SingletonClass();
_objList = new List<object>();
}
return _singletonClass;
}
}
}
public List<obj> GetList()
{
lock(_lockObjList)
{
return _objList;
}
}
public void UpdateProgress(int index, double value)
{
lock(_lockObjList)
{
_objList[index].Progress = value;
}
}
public void SetList(List<obj> objs)
{
lock(_lockObjList)
{
_objList = objs;
}
}
}
public class MessageHandler : HubInvoker<MessageHub>
{
public MessageHandler () {}
public void OnReceiveMessage(object sender, MessageArgs args)
{
var list = SingletonClass.Instance.GetList();
if(list != null){
var i = 0;
for(; i < list.Length && list[i].Id == args.Id; i++);
if(i < list.Length)
{
SingletonClass.Instance.UpdateProgress(i, args.Progress);
}
}
}
}
public class ObjController
{
public ObjController() {}
public void SetList(List<obj> objs)
{
SingletonClass.Instance.SetList(objs);
}
}
EDITED
I've added some codes above for more information of my implementation.