What is the difference between SynchronizedCollection and the other concurrent collections?

前端 未结 1 1127
眼角桃花
眼角桃花 2020-12-02 20:07

How does SynchronizedCollection and the concurrent collections in the System.Collections.Concurrent namespace differ from each other, apar

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 20:27

    The SynchronizedCollection class was introduced first in .NET 2.0 to provide a thread-safe collection class. It does this via locking so that you essentially have a List where every access is wrapped in a lock statement.

    The System.Collections.Concurrent namespace is much newer. It wasn't introduced until .NET 4.0 and it includes a substantially improved and more diverse set of choices. These classes no longer use locks to provide thread safety, which means they should scale better in a situation where multiple threads are accessing their data simultaneously. However, a class implementing the IList interface is notably absent among these options.

    So, if you're targeting version 4.0 of the .NET Framework, you should use one of the collections provided by the System.Collections.Concurrent namespace whenever possible. Just as with choosing between the various types of collections provided in the System.Collections.Generic namespace, you'll need to choose the one whose features and characteristics best fit your specific needs.

    If you're targeting an older version of the .NET Framework or need a collection class that implements the IList interface, you'll have to opt for the SynchronizedCollection class.

    This article on MSDN is also worth a read: When to Use a Thread-Safe Collection

    0 讨论(0)
提交回复
热议问题