none
internal static IList<T> Synchronized(List<T> list) RRS feed

  • Question

  • Is there a reason that this method is internal ?

    Hashtable, SortedList have the same method but public. 

    Monday, September 10, 2012 5:39 PM

Answers

  • Hashtable and SortedList are the old (pre .NET 2.0), nongeneric collections. All those old collections have this method but all the new, generic ones (List<T>, Dictionary<T>, etc) do not have this method.

    The synchronized collections returned by that method are nothing more than simple wrappers around the original collection that use lock to synchronize access. This is something that you can do yourself easily and with more flexibility.

    In addition their inherit simplicity made some people think that if they use such collections they got all thread safety issue covered. But that's not the case, the lock only protects the collection itself from corruption but it can't deal with multiple collection operations that may need to be done atomically in some cases. For example if you try to ensure that you don't add duplicates then you can't simply do:

    if (!collection.Contains(x)) collection.Add(x);

    For this to work correctly you need a lock around Contains/Add.

    Monday, September 10, 2012 6:00 PM
    Moderator