Recently I switched from HashSet to a collection someone else posted called 'ConcurrentHashSet', I decided to opt out of locking my own HashSet as I was using it a lot and just seemed a safer bet to use a pre-made thread-safe class, but I've hit an issue.
When I used HashSet (the default HashSet class) I was getting my HashSet values using the First
and FirstOrDefault
methods, the issue is I can no longer use these methods and I'm not sure why or how to re-implement them, is it even possible? It may be really simple, I'm unsure.
I was hoping someone would know and could point me in the right direction. Heres the class that I picked up off another stack overflow answer, although I'm not sure if this is the original.
public class ConcurrentHashSet<T> : IDisposable
{
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
private readonly HashSet<T> _hashSet = new HashSet<T>();
public bool TryAdd(T item)
{
_lock.EnterWriteLock();
try
{
return _hashSet.Add(item);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
public void Clear()
{
_lock.EnterWriteLock();
try
{
_hashSet.Clear();
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
public bool Contains(T item)
{
_lock.EnterReadLock();
try
{
return _hashSet.Contains(item);
}
finally
{
if (_lock.IsReadLockHeld) _lock.ExitReadLock();
}
}
public bool TryRemove(T item)
{
_lock.EnterWriteLock();
try
{
return _hashSet.Remove(item);
}
finally
{
if (_lock.IsWriteLockHeld) _lock.ExitWriteLock();
}
}
public int Count
{
get
{
_lock.EnterReadLock();
try
{
return _hashSet.Count;
}
finally
{
if (_lock.IsReadLockHeld) _lock.ExitReadLock();
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_lock?.Dispose();
}
}
~ConcurrentHashSet()
{
Dispose(false);
}
}