Thread safe list
Thread-safe List<T> property
回答1
If you are targetting .Net 4 there are a few options in System.Collections.Concurrent Namespace
You could use ConcurrentBag<T>
in this case instead of List<T>
回答2
Even as it got the most votes, one usually can't take System.Collections.Concurrent.ConcurrentBag<T>
as a thread-safe replacement for System.Collections.Generic.List<T>
as it is (Radek Stromský already pointed it out) not ordered.
But there is a class called System.Collections.Generic.SynchronizedCollection<T>
that is already since .NET 3.0 part of the framework, but it is that well hidden in a location where one does not expect it that it is little known and probably you have never ever stumbled over it (at least I never did).
SynchronizedCollection<T>
is compiled into assembly System.ServiceModel.dll (which is part of the client profile but not of the portable class library).
Hope that helps.
ArrayList.Synchronized Method
Returns a list wrapper that is synchronized (thread safe).
To guarantee the thread safety of the ArrayList, all operations must be done through this wrapper.
Enumerating through a collection is intrinsically本质上 not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.
Thread-Safe Collections
The .NET Framework 4 introduces the System.Collections.Concurrent namespace, which includes several collection classes that are both thread-safe and scalable. Multiple threads can safely and efficiently add or remove items from these collections, without requiring additional synchronization in user code.仅仅是线程安全添加和删除元素,但是如果在遍历集合的过程中做这个操作,还是会报错的。 When you write new code, use the concurrent collection classes whenever multiple threads will write to the collection concurrently. If you are only reading from a shared collection, then you can use the classes in the System.Collections.Generic namespace. We recommend that you do not use 1.0 collection classes unless you are required to target the .NET Framework 1.1 or earlier runtime.
Thread Synchronization in the .NET Framework 1.0 and 2.0 Collections
The collections introduced in the .NET Framework 1.0 are found in the System.Collections namespace. These collections, which include the commonly used ArrayList and Hashtable, provide some thread-safety through the Synchronized
property, which returns a thread-safe wrapper around the collection. The wrapper works by locking the entire collection on every add or remove operation. Therefore, each thread that is attempting to access the collection must wait for its turn to take the one lock. This is not scalable and can cause significant performance degradation降级 for large collections. Also, the design is not completely protected from race conditions. For more information, see Synchronization in Generic Collections.
The collection classes introduced in the .NET Framework 2.0 are found in the System.Collections.Generic namespace. These include List<T>, Dictionary<TKey,TValue>, and so on. These classes provide improved type safety and performance compared to the .NET Framework 1.0 classes. However, the .NET Framework 2.0 collection classes do not provide any thread synchronization; user code must provide all synchronization when items are added or removed on multiple threads concurrently.
We recommend the concurrent collections classes in the .NET Framework 4 because they provide not only the type safety of the .NET Framework 2.0 collection classes, but also more efficient and more complete thread safety than the .NET Framework 1.0 collections provide.
Fine-Grained Locking and Lock-Free Mechanisms
Some of the concurrent collection types use lightweight synchronization mechanisms such as SpinLock, SpinWait, SemaphoreSlim, and CountdownEvent, which are new in the .NET Framework 4. These synchronization types typically use busy spinning for brief periods before they put the thread into a true Wait state. When wait times are expected to be very short, spinning is far less computationally expensive than waiting, which involves an expensive kernel transition. For collection classes that use spinning, this efficiency means that multiple threads can add and remove items at a very high rate. For more information about spinning vs. blocking, see SpinLock and SpinWait.
The ConcurrentQueue<T> and ConcurrentStack<T> classes do not use locks at all. Instead, they rely on Interlocked operations to achieve thread-safety.
Because the concurrent collections classes support ICollection, they provide implementations for the IsSynchronized and SyncRoot properties, even though these properties are irrelevant. IsSynchronized
always returns false
and SyncRoot
is always null
(Nothing
in Visual Basic). 只是因为实现了接口,所以有对应的属性,但是属性是完全没用的。
The following table lists the collection types in the System.Collections.Concurrent namespace.
Type | Description |
---|---|
BlockingCollection<T> | Provides bounding and blocking functionality for any type that implements IProducerConsumerCollection<T>. For more information, see BlockingCollection Overview. |
ConcurrentDictionary<TKey,TValue> | Thread-safe implementation of a dictionary of key-value pairs. |
ConcurrentQueue<T> | Thread-safe implementation of a FIFO (first-in, first-out) queue. |
ConcurrentStack<T> | Thread-safe implementation of a LIFO (last-in, first-out) stack. |
ConcurrentBag<T> | Thread-safe implementation of an unordered collection of elements. |
IProducerConsumerCollection<T> | The interface that a type must implement to be used in a BlockingCollection . |
Related Topics
Title | Description |
---|---|
BlockingCollection Overview | Describes the functionality provided by the BlockingCollection<T> type. |
How to: Add and Remove Items from a ConcurrentDictionary | Describes how to add and remove elements from a ConcurrentDictionary<TKey,TValue> |
How to: Add and Take Items Individually from a BlockingCollection | Describes how to add and retrieve items from a blocking collection without using the read-only enumerator. |
How to: Add Bounding and Blocking Functionality to a Collection | Describes how to use any collection class as the underlying storage mechanism for an IProducerConsumerCollection<T> collection. |
How to: Use ForEach to Remove Items in a BlockingCollection | Describes how to use foreach , (For Each in Visual Basic) to remove all items in a blocking collection. |
How to: Use Arrays of Blocking Collections in a Pipeline | Describes how to use multiple blocking collections at the same time to implement a pipeline. |
How to: Create an Object Pool by Using a ConcurrentBag | Shows how to use a concurrent bag to improve performance in scenarios where you can reuse objects instead of continually creating new ones. |
Reference
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2019-05-07 hasvalue vs !=null
2019-05-07 Procedure or function 'pu_usr_User' expects parameter '@WhiteIp', which was not supplied.
2018-05-07 .net core迁移