ThreadSafeHashSetT Class

Implements a thread-safe hash set, which has similar characteristics to ThreadSafeDictionaryTKey, TValue. It can be a good alternative for HashSetT, LockingCollectionT, or when one would use a ConcurrentDictionaryTKey, TValue with ignored values.

Definition

Namespace: KGySoft.Collections
Assembly: KGySoft.CoreLibraries (in KGySoft.CoreLibraries.dll) Version: 8.1.0
C#
[SerializableAttribute]
public class ThreadSafeHashSet<T> : ICollection<T>, 
	IEnumerable<T>, IEnumerable, ICollection, ISerializable, IDeserializationCallback, 
	IReadOnlyCollection<T>
Inheritance
Object    ThreadSafeHashSetT
Implements
ICollectionT, IEnumerableT, IReadOnlyCollectionT, ICollection, IEnumerable, IDeserializationCallback, ISerializable

Type Parameters

T
Type of the items stored in the ThreadSafeHashSetT.

Remarks

ThreadSafeHashSetT uses a very similar approach to ThreadSafeDictionaryTKey, TValue. It uses two separate internal storage: new items are added to a temporary storage using a single lock, which might regularly be merged into a faster lock-free storage, depending on the value of the MergeInterval property. Once the items are merged, their access (both read and write) becomes lock free. Even deleting and re-adding an item becomes faster after it has been merged into the lock-free storage.

  Note

Therefore, ThreadSafeHashSetT is not always a good alternative of LockingCollectionT, or even a ConcurrentDictionaryTKey, TValue with ignored values. If new items are continuously added, then always a shared lock is used, in which case ConcurrentDictionaryTKey, TValue might perform better, unless you need to use some members, which are very slow in ConcurrentDictionaryTKey, TValue (see the performance comparison table at the Remarks section of the ThreadSafeDictionaryTKey, TValue class). If the newly added elements are regularly removed, make sure the PreserveMergedItems property is ; otherwise, the already merged items are just marked deleted when removed from the ThreadSafeHashSetT or when you call the Clear method. To remove even the merged items you must call the Reset method, or to remove the deleted items only you can explicitly call the TrimExcess method.

Comparison with other thread-safe collections.

When to prefer ThreadSafeHashSetT over ConcurrentDictionaryTKey, TValue:

  • If you would use only the keys, without any value.
  • If it is known that a fixed number of items will be used, or Contains will be used much more often than Add, in which case ThreadSafeHashSetT may become mainly lock-free.
  • If the same set of items are deleted and re-added again and again. In this case consider to set the PreserveMergedItems to , so it is not checked whether a cleanup should be performed due to many deleted items.
  • If it is needed to access Count, enumerate the items or you need to call ToArray, which are particularly slow in case of ConcurrentDictionaryTKey, TValue.
  • If it is expected that there will be many hash collisions.
  • If the collection is needed to be serialized.

When to prefer LockingCollectionT over ThreadSafeHashSetT:

  • If you just need a wrapper for an already existing ICollectionT without copying the actual items.
  • If you just need a simple thread-safe solution without additional allocations (unless if you enumerate the collection) and it's not a problem if it cannot scale well for high concurrency.

Incompatibilities with HashSetT:

  • Some of the constructors have different parameters.
  • ThreadSafeHashSetT does not implement the ISetT interface because most of its members make little sense when the instance is used concurrently.
  • It has no public CopyTo methods. The ICollection<T>.CopyTo method is implemented explicitly, though it is not recommended to use it because when elements are added or removed during the operation you cannot tell how many elements were actually copied. Use the ToArray method instead, which works in all circumstances.

Constructors

ThreadSafeHashSetT Initializes a new instance of the ThreadSafeHashSetT class that is empty and uses the default comparer and Auto hashing strategy.
ThreadSafeHashSetT(IEqualityComparerT, HashingStrategy) Initializes a new instance of the ThreadSafeHashSetT class that is empty and uses the specified comparer and hashing strategy.
ThreadSafeHashSetT(Int32, HashingStrategy) Initializes a new instance of the ThreadSafeHashSetT class that is empty and uses the default comparer and the specified hashing strategy.
ThreadSafeHashSetT(SerializationInfo, StreamingContext) Initializes a new instance of the ThreadSafeHashSetT class from serialized data.
ThreadSafeHashSetT(IEnumerableT, IEqualityComparerT, HashingStrategy) Initializes a new instance of the ThreadSafeHashSetT class from the specified collection and uses the specified comparer and hashing strategy.
ThreadSafeHashSetT(Int32, IEqualityComparerT, HashingStrategy) Initializes a new instance of the ThreadSafeHashSetT class that is empty and uses the specified comparer and hashing strategy.

Properties

Comparer Gets the IEqualityComparerT that is used to determine equality of items for this ThreadSafeHashSetT.
Count Gets the number of elements contained in this ThreadSafeHashSetT.
IsEmpty Gets whether this ThreadSafeHashSetT is empty.
MergeInterval Gets or sets the minimum lifetime for the temporarily created internal locking storage when adding new items to the ThreadSafeHashSetT.
Default value: 100 milliseconds.
PreserveMergedItems Gets or sets whether items that have already been merged into the faster lock-free storage are preserved even when they are deleted.
Default value: .

Methods

Add Adds the specified item to the ThreadSafeHashSetT.
Clear Removes all items from the ThreadSafeHashSetT.
Contains Determines whether the ThreadSafeHashSetT contains the specified item.
EnsureMerged Ensures that all elements in this ThreadSafeHashSetT are merged into the faster lock-free storage.
See the Remarks section of the MergeInterval property for details.
GetEnumerator Returns an enumerator that iterates through the items of this ThreadSafeHashSetT.
GetObjectData In a derived class populates a SerializationInfo with the additional data of the derived type needed to serialize the target object.
OnDeserialization In a derived class restores the state the deserialized instance.
Remove Tries to remove the specified item from the ThreadSafeHashSetT.
Reset Removes all items from the ThreadSafeHashSetT.
See the Remarks section of the Clear method for details.
ToArray Copies the items stored in the ThreadSafeHashSetT to a new array.
TrimExcess Forces to perform a merge while removing all possibly allocated but already deleted entries from the lock-free storage, even if the PreserveMergedItems property is .
See the Remarks section of the PreserveMergedItems property for details.
TryAdd Tries to add the specified item to the ThreadSafeHashSetT.
TryGetValue Tries to get the actual stored item for the specified equalValue in the ThreadSafeHashSetT. It can be useful to obtain the actually stored reference when the Comparer can consider different instances equal.
TryRemove Tries to remove the specified item from the ThreadSafeHashSetT.

Extension Methods

AddRangeT Adds a collection to the target ICollectionT.
(Defined by CollectionExtensions)
AsThreadSafeT Returns a LockingCollectionT, which provides a thread-safe wrapper for the specified collection. This only means that if the members are accessed through the returned LockingCollectionT, then the inner state of the wrapped collection remains always consistent and not that all of the multi-threading concerns can be ignored.
See the Remarks section of the LockingCollectionT class for details and some examples.
(Defined by CollectionExtensions)
Convert Converts an Object specified in the obj parameter to the desired targetType.
See the Examples section of the generic ConvertTTarget(Object, CultureInfo) overload for an example.
(Defined by ObjectExtensions)
ConvertTTarget Converts an Object specified in the obj parameter to the desired TTarget.
(Defined by ObjectExtensions)
ForEachT Similarly to the List<T>.ForEach method, processes an action on each element of an enumerable collection.
(Defined by EnumerableExtensions)
GetRandomElementT Gets a random element from the enumerable source using a new FastRandom instance.
(Defined by EnumerableExtensions)
GetRandomElementT Gets a random element from the enumerable source using a specified Random instance.
(Defined by EnumerableExtensions)
In Gets whether item is among the elements of set.
See the Examples section of the generic InT(T, T) overload for an example.
(Defined by ObjectExtensions)
IndexOf Searches for an element in the source enumeration where the specified predicate returns .
(Defined by EnumerableExtensions)
IndexOf Searches for an element in the source enumeration.
(Defined by EnumerableExtensions)
IndexOfT Searches for an element in the source enumeration where the specified predicate returns .
(Defined by EnumerableExtensions)
IndexOfT Searches for an element in the source enumeration.
(Defined by EnumerableExtensions)
IsNullOrEmpty Determines whether the specified source is or empty (has no elements).
(Defined by EnumerableExtensions)
IsNullOrEmptyT Determines whether the specified source is or empty (has no elements).
(Defined by EnumerableExtensions)
JoinT Concatenates the items of the source collection into a new string instance using the specified separator between the items.
(Defined by EnumerableExtensions)
JoinT Concatenates the items of the source collection into a new string instance using the specified separator between the items.
(Defined by EnumerableExtensions)
ShuffleT Shuffles an enumerable source (randomizes its elements) using a new FastRandom instance.
(Defined by EnumerableExtensions)
ShuffleT Shuffles an enumerable source (randomizes its elements) using the provided seed with a new FastRandom instance.
(Defined by EnumerableExtensions)
ShuffleT Shuffles an enumerable source (randomizes its elements) using the provided seed with a new FastRandom instance.
(Defined by EnumerableExtensions)
ShuffleT Shuffles an enumerable source (randomizes its elements) using a specified Random instance.
(Defined by EnumerableExtensions)
ToCircularListT Creates a CircularListT from an IEnumerableT.
(Defined by EnumerableExtensions)
ToStringKeyedDictionaryT Creates a StringKeyedDictionaryTValue from an IEnumerableT instance using the specified keySelector delegate and a comparer.
(Defined by EnumerableExtensions)
ToStringKeyedDictionaryT, TValue Creates a StringKeyedDictionaryTValue from an IEnumerableT instance using the specified key and value selector delegates and a comparer.
(Defined by EnumerableExtensions)
TryAdd Tries to add the specified item to the collection.
(Defined by EnumerableExtensions)
TryAddT Tries to add the specified item to the collection.
(Defined by EnumerableExtensions)
TryAddRange Tries to add the specified collection to the target collection.
(Defined by EnumerableExtensions)
TryAddRangeT Tries to add the specified collection to the target collection.
(Defined by EnumerableExtensions)
TryClear Tries to remove all elements from the collection.
(Defined by EnumerableExtensions)
TryClearT Tries to remove all elements from the collection.
(Defined by EnumerableExtensions)
TryConvert Tries to convert an Object specified in the obj parameter to the desired targetType.
See the Examples section of the ConvertTTarget(Object, CultureInfo) method for a related example.
(Defined by ObjectExtensions)
TryConvert Tries to convert an Object specified in the obj parameter to the desired targetType.
See the Examples section of the ConvertTTarget(Object, CultureInfo) method for a related example.
(Defined by ObjectExtensions)
TryConvertTTarget Tries to convert an Object specified in the obj parameter to the desired TTarget.
See the Examples section of the ConvertTTarget(Object, CultureInfo) method for a related example.
(Defined by ObjectExtensions)
TryConvertTTarget Tries to convert an Object specified in the obj parameter to the desired TTarget.
See the Examples section of the ConvertTTarget(Object, CultureInfo) method for a related example.
(Defined by ObjectExtensions)
TryGetCount Tries to get the number of elements in the source enumeration without enumerating it.
(Defined by EnumerableExtensions)
TryGetCountT Tries to get the number of elements in the source enumeration without enumerating it.
(Defined by EnumerableExtensions)
TryGetElementAt Tries to get an item at the specified index in the collection.
(Defined by EnumerableExtensions)
TryGetElementAtT Tries to get an item at the specified index in the collection.
(Defined by EnumerableExtensions)
TryInsert Tries to insert the specified item at the specified index to the collection.
(Defined by EnumerableExtensions)
TryInsertT Tries to insert the specified item at the specified index to the collection.
(Defined by EnumerableExtensions)
TryInsertRange Tries to insert the specified collection into the target collection.
(Defined by EnumerableExtensions)
TryInsertRangeT Tries to insert the specified collection into the target collection.
(Defined by EnumerableExtensions)
TryRemove Tries to remove the specified item from to the collection.
(Defined by EnumerableExtensions)
TryRemoveT Tries to remove the specified item from to the collection.
(Defined by EnumerableExtensions)
TryRemoveAt Tries to remove an item at the specified index from the collection.
(Defined by EnumerableExtensions)
TryRemoveAtT Tries to remove an item at the specified index from the collection.
(Defined by EnumerableExtensions)
TryRemoveRange Tries to remove count amount of items from the specified collection at the specified index.
(Defined by EnumerableExtensions)
TryRemoveRangeT Tries to remove count amount of items from the specified collection at the specified index.
(Defined by EnumerableExtensions)
TryReplaceRange Tries to remove count amount of items from the target at the specified index, and to insert the specified collection at the same position. The number of elements in collection can be different from the amount of removed items.
(Defined by EnumerableExtensions)
TryReplaceRangeT Tries to remove count amount of items from the target at the specified index, and to insert the specified collection at the same position. The number of elements in collection can be different from the amount of removed items.
(Defined by EnumerableExtensions)
TrySetElementAt Tries to set the specified item at the specified index in the collection.
(Defined by EnumerableExtensions)
TrySetElementAtT Tries to set the specified item at the specified index in the collection.
(Defined by EnumerableExtensions)

Thread Safety

Static members of this type are safe for multi-threaded operations. Instance members of this type are safe for multi-threaded operations.

See Also