What is the point of those calls to Contains()
? They don't do anything. If you want to add only if the set does not contain an item, then you can do the following:
if(!hasSet.Contains(h))
{
lock(hashSetLock)
{
if(!hasSet.Contains(h))
{
hashSet.Add(h);
}
}
}
With this code you don't lock to check the existing of the element, but if the element was not set you have to check again after locking. What do you gain? You don't lock in case the element already exists.