Collections Collections
Collections Collections
DocFX + Singulink = ♥

Search Results for

    Method AsSafeEnumerable

    AsSafeEnumerable<TKey, TValue>(ConcurrentDictionary<TKey, TValue>)

    Wraps a ConcurrentDictionary<TKey, TValue> in an IEnumerable<T> that is safe to pass to consumers which may otherwise corrupt or fail when the dictionary is modified concurrently during enumeration.

    Declaration
    public static IEnumerable<KeyValuePair<TKey, TValue>> AsSafeEnumerable<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary) where TKey : notnull
    Parameters
    Type Name Description
    ConcurrentDictionary<TKey, TValue> dictionary

    The dictionary to wrap.

    Returns
    Type Description
    IEnumerable<KeyValuePair<TKey, TValue>>

    An IEnumerable<T> that enumerates the key-value pairs in the dictionary.

    Type Parameters
    Name Description
    TKey

    The type of the keys in the dictionary.

    TValue

    The type of the values in the dictionary.

    Remarks

    While directly enumerating a ConcurrentDictionary<TKey, TValue> is safe even if it is modified concurrently, many BCL methods that operate on IEnumerable<T> attempt to cast it to ICollection<T> (which ConcurrentDictionary<TKey, TValue> implements) as an optimization. That optimization can cause silent corruption or exceptions if the dictionary is modified concurrently.

    Wrapping the dictionary with this method hides the ICollection<T> implementation so it can be safely passed to any method that accepts an IEnumerable<T>, such as LINQ operators and collection constructors, without risking corruption or exceptions due to concurrent modifications.

    © Singulink. All rights reserved.