I have a class extending the Dictionary class. This class is used for storing some information (modeled in CustomClass) and accessing it through an integer ID.
To extend this class I have added a TryAdd method, specific to my workflow, which implement different behaviours for the cases of trying to add a new or a already existing CustomClass object.
public class CustomDictionary : Dictionary<int, CustomClass>
{
private void TryAdd(int ID, CustomClass customObject)
{
if (this.ContainsKey(ID))
{
//some operations
}
else
{
//some others operations
this.Add(customObject);
}
}
}
There will be only one instance object for this class. I want to add locks to provide thread safety and syncronisation for the object of type CustomDictionary.
TryAdd and data accessing operation will frequently occur in parallel for this structure.
Have in mind that at the moment I can't use framework 4.0 so I can't use ConcurrentCollections.
To ensure thread safety I put this.Add(customObject); within a lock(this) but I have read that this is very bad.
Then I read about locking using a private object.
public class CustomDictionary : Dictionary<int, CustomClass>
{
private object lockObject = new Object();
private void TryAdd(int ID, CustomClass customObject)
{
if (this.ContainsKey(ID))
{
//some operations
}
else
{
//some others operations
lock(lockObject)
{
this.Add(customObject);
}
}
}
}
Is this the good way of doing it? Should I also lock the CustomDictionary object when I read data from that object?
Any improvements for the implementation of this class would be helpfull.
lock(lockObject)\$\endgroup\$lock(object)was a mistake. \$\endgroup\$