KGy SOFT

LockingCollectionT Class

KGy SOFT Core Libraries Help
Provides a simple wrapper for an ICollectionT where all members are thread-safe. This only means that 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 for details and some examples.
Inheritance Hierarchy

SystemObject
  KGySoft.CollectionsLockingCollectionT
    KGySoft.CollectionsLockingDictionaryTKey, TValue
    KGySoft.CollectionsLockingListT

Namespace:  KGySoft.Collections
Assembly:  KGySoft.CoreLibraries (in KGySoft.CoreLibraries.dll) Version: 5.0.0-rc.1
Syntax

[SerializableAttribute]
public class LockingCollection<T> : ICollection<T>, 
	IEnumerable<T>, IEnumerable

Type Parameters

T
The type of the elements in the collection.

The LockingCollectionT type exposes the following members.

Constructors

  NameDescription
Public methodLockingCollectionT
Initializes a new instance of the LockingCollectionT class with a HashSetT inside.
Public methodLockingCollectionT(ICollectionT)
Initializes a new instance of the LockingCollectionT class.
Top
Properties

  NameDescription
Public propertyCount
Gets the number of elements contained in the LockingCollectionT.
Public propertyIsReadOnly
Gets a value indicating whether the LockingCollectionT is read-only.
Top
Methods

  NameDescription
Public methodAdd
Adds an item to the LockingCollectionT.
Public methodClear
Removes all items from the LockingCollectionT.
Public methodContains
Determines whether the LockingCollectionT contains a specific value.
Public methodCopyTo
Copies the elements of the LockingCollectionT to an Array, starting at a particular arrayIndex.
Public methodEquals
Determines whether the specified object is equal to the current object.
(Inherited from Object.)
Protected methodFinalize
Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
(Inherited from Object.)
Public methodGetEnumerator
Returns an enumerator that iterates through the collection.
Public methodGetHashCode
Serves as the default hash function.
(Inherited from Object.)
Public methodGetType
Gets the Type of the current instance.
(Inherited from Object.)
Public methodLock
Locks the access of the underlying collection from other threads until Unlock is called as many times as this method was called. Needed to be called if multiple calls to the wrapped collection have to be combined without releasing the lock between each calls.
See the Remarks section of the LockingCollectionT class for details and some examples.
Protected methodMemberwiseClone
Creates a shallow copy of the current Object.
(Inherited from Object.)
Public methodRemove
Removes the first occurrence of a specific object from the LockingCollectionT.
Public methodToString
Returns a string that represents the current object.
(Inherited from Object.)
Public methodUnlock
When called as many times as Lock was called previously, then unlocks the access of the underlying collection so other threads also can access it.
Top
Extension Methods

  NameDescription
Public Extension MethodAddRangeT (Defined by CollectionExtensions.)
Public Extension MethodAsThreadSafeT
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.)
Public Extension MethodConvert(Type, CultureInfo)Overloaded.
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.)
Public Extension MethodCode exampleConvertTTarget(CultureInfo)Overloaded.
Converts an Object specified in the obj parameter to the desired TTarget.
(Defined by ObjectExtensions.)
Public Extension MethodForEachT
Similarly to the List<T>.ForEach method, processes an action on each element of an enumerable collection.
(Defined by EnumerableExtensions.)
Public Extension MethodGetRandomElementT(Boolean)Overloaded.
Gets a random element from the enumerable source using a new Random instance.
(Defined by EnumerableExtensions.)
Public Extension MethodGetRandomElementT(Random, Boolean)Overloaded.
Gets a random element from the enumerable source using a specified Random instance.
(Defined by EnumerableExtensions.)
Public Extension MethodIn (Defined by ObjectExtensions.)
Public Extension MethodIndexOf(FuncObject, Boolean)Overloaded.
Searches for an element in the source enumeration where the specified predicate returns .
(Defined by EnumerableExtensions.)
Public Extension MethodIndexOf(Object)Overloaded.
Searches for an element in the source enumeration.
(Defined by EnumerableExtensions.)
Public Extension MethodIndexOfT(FuncT, Boolean)Overloaded.
Searches for an element in the source enumeration where the specified predicate returns .
(Defined by EnumerableExtensions.)
Public Extension MethodIndexOfT(T)Overloaded.
Searches for an element in the source enumeration.
(Defined by EnumerableExtensions.)
Public Extension MethodIsNullOrEmptyOverloaded.
Determines whether the specified source is  or empty (has no elements).
(Defined by EnumerableExtensions.)
Public Extension MethodIsNullOrEmptyTOverloaded.
Determines whether the specified source is  or empty (has no elements).
(Defined by EnumerableExtensions.)
Public Extension MethodShuffleTOverloaded.
Shuffles an enumerable source (randomizes its elements) using a new Random instance.
(Defined by EnumerableExtensions.)
Public Extension MethodShuffleT(Int32)Overloaded.
Shuffles an enumerable source (randomizes its elements) using the provided seed with a new Random instance.
(Defined by EnumerableExtensions.)
Public Extension MethodShuffleT(Random)Overloaded.
Shuffles an enumerable source (randomizes its elements) using a specified Random instance.
(Defined by EnumerableExtensions.)
Public Extension MethodToCircularListT (Defined by EnumerableExtensions.)
Public Extension MethodTryAdd(Object, Boolean, Boolean)Overloaded.
Tries to add the specified item to the collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTryAddT(T, Boolean, Boolean)Overloaded.
Tries to add the specified item to the collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTryAddRange(IEnumerable, Boolean, Boolean)Overloaded.
Tries to add the specified collection to the target collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTryAddRangeT(IEnumerableT, Boolean, Boolean)Overloaded.
Tries to add the specified collection to the target collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTryClear(Boolean, Boolean)Overloaded.
Tries to remove all elements from the collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTryClearT(Boolean, Boolean)Overloaded.
Tries to remove all elements from the collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTryConvert(Type, Object)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired targetType.
(Defined by ObjectExtensions.)
Public Extension MethodTryConvert(Type, CultureInfo, Object)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired targetType.
(Defined by ObjectExtensions.)
Public Extension MethodTryConvertTTarget(TTarget)Overloaded.
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.)
Public Extension MethodTryConvertTTarget(CultureInfo, TTarget)Overloaded.
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.)
Public Extension MethodTryGetElementAt(Int32, Object, Boolean, Boolean)Overloaded.
Tries to get an item at the specified index in the collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTryGetElementAtT(Int32, T, Boolean, Boolean)Overloaded.
Tries to get an item at the specified index in the collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTryInsert(Int32, Object, Boolean, Boolean)Overloaded.
Tries to insert the specified item at the specified index to the collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTryInsertT(Int32, T, Boolean, Boolean)Overloaded.
Tries to insert the specified item at the specified index to the collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTryInsertRange(Int32, IEnumerable, Boolean, Boolean)Overloaded.
Tries to insert the specified collection into the target collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTryInsertRangeT(Int32, IEnumerableT, Boolean, Boolean)Overloaded.
Tries to insert the specified collection into the target collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTryRemove(Object, Boolean, Boolean)Overloaded.
Tries to remove the specified item from to the collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTryRemoveT(T, Boolean, Boolean)Overloaded.
Tries to remove the specified item from to the collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTryRemoveAt(Int32, Boolean, Boolean)Overloaded.
Tries to remove an item at the specified index from the collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTryRemoveAtT(Int32, Boolean, Boolean)Overloaded.
Tries to remove an item at the specified index from the collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTryRemoveRange(Int32, Int32, Boolean, Boolean)Overloaded.
Tries to remove count amount of items from the specified collection at the specified index.
(Defined by EnumerableExtensions.)
Public Extension MethodTryRemoveRangeT(Int32, Int32, Boolean, Boolean)Overloaded.
Tries to remove count amount of items from the specified collection at the specified index.
(Defined by EnumerableExtensions.)
Public Extension MethodTryReplaceRange(Int32, Int32, IEnumerable, Boolean, Boolean)Overloaded.
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.)
Public Extension MethodTryReplaceRangeT(Int32, Int32, IEnumerableT, Boolean, Boolean)Overloaded.
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.)
Public Extension MethodTrySetElementAt(Int32, Object, Boolean, Boolean)Overloaded.
Tries to set the specified item at the specified index in the collection.
(Defined by EnumerableExtensions.)
Public Extension MethodTrySetElementAtT(Int32, T, Boolean, Boolean)Overloaded.
Tries to set the specified item at the specified index in the collection.
(Defined by EnumerableExtensions.)
Top
Remarks

Type safety means that all members of the underlying collection are accessed in a lock, which only provides that the collection remains consistent as long as it is accessed only by the members of this class. This does not solve every issue of multi-threading automatically. Consider the following example:

C#
var asThreadSafe = new LockingCollection<MyClass>(myCollection);

// Though both calls use locks it still can happen that two threads add the same item twice this way
// because the lock is released between the two calls:
if (!asThreadSafe.Contains(myItem))
    asThreadSafe.Add(myItem);

For the situations above a lock can be requested also explicitly by the Lock method, which can be released by the Unlock method. To release an explicitly requested lock the Unlock method must be called the same times as the Lock method. The fixed version of the example above:

C#
var asThreadSafe = new LockingCollection<MyClass>(myCollection);

// This works well because the lock is not released between the two calls:
asThreadSafe.Lock();
try
{
    if (!asThreadSafe.Contains(myItem))
        asThreadSafe.Add(myItem);
}
finally
{
    asThreadSafe.Unlock();
}

To avoid confusion, the non-generic ICollection interface is not implemented by the LockingCollectionT class because it uses a different aspect of synchronization.

The GetEnumerator method creates a snapshot of the underlying collection so obtaining the enumerator has an O(n) cost on this class.

Note Note
Starting with .NET 4 a sort of concurrent collections appeared. While they provide good scalability for multiple concurrent readers by using separate locks for entries or for a set of entries, in many situations they perform worse than a simple locking collection, especially if the collection to lock uses a fast accessible storage (eg. an array) internally. It also may worth to mention that some members (such as the Count property) are surprisingly expensive operations on most concurrent collections as they traverse the inner storage and in the meantime they lock all entries while counting the elements. So it always depends on the concrete scenario whether a simple locking collection or a concurrent collection is more beneficial to use.

Thread Safety

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

Reference