I have the following code. When deployed to a server, i m getting exception that , this object already exists in the dictionary. Even though , i did double locking, synchrony didnt work quite well. What s the best way to implement this? How can i best lock access to this section? Should i implement a singleton class and place the methods in there?
Should i lock the collection or mutex?
NO I M NOT ON .NET 4
As you can see, i m trying to do a simple cache based on datetime.
// within the class.
IDictionary<id, MyObj> _mydict = new Dictionary<string, MyObj>();
object mutex = new object;
//within some method comes the following
if (_mydict.TryGetValue(id, out myobj))
{
DateTime now = DateTime.Now;
DateTime expiry = myobj.Timestamp;
TimeSpan span = now.Subtract(expiry);
if (span.Minutes 0)
{
lock (mutex)
{
myobj= DataAccess.GetMyObj(id);
_mydict[id] = myobj;
}
return myobj;
}
else
{
return myobj;
}
}
else
{
lock (mutex)
{
if (_mydict.TryGetValue(id, out myobj))
{
return myobj;
}
else
{
lock (mutex)
{
myobj = DataAccess.GetMyObj(id);
_mydict[id] = myobj;
}
return myobj;
}
}
}