ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C# 线程安全的集合

2021-08-04 08:01:58  阅读:256  来源: 互联网

标签:use thread C# collection classes Collections 集合 线程 NET


参考网址: https://docs.microsoft.com/en-us/dotnet/standard/collections/thread-safe/

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 SpinLockSpinWaitSemaphoreSlim, 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.

 Note

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.

FINE-GRAINED LOCKING AND LOCK-FREE MECHANISMS
TypeDescription
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
TitleDescription
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

System.Collections.Concurrent


Recommended content

  • ConcurrentQueue<T> Class (System.Collections.Concurrent)

    Represents a thread-safe first in-first out (FIFO) collection.

  • ConcurrentBag<T> Class (System.Collections.Concurrent)

    Represents a thread-safe, unordered collection of objects.

  • When to Use a Thread-Safe Collection

    Know when to use a thread-safe collection in .NET. There are 5 collection types that are specially designed to support multithreaded add & remove operations.

  •  

标签:use,thread,C#,collection,classes,Collections,集合,线程,NET
来源: https://www.cnblogs.com/bruce1992/p/15097216.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有