C# 多线程安全集合类
System.Collections.Concurrent 命名空间下提供多个线程安全集合类,只要多个线程同时访问集合,就应使用这些类来代替 System.Collections 和 System.Collections.Generic 命名空间中的相应类型。 但是,不保证通过扩展方法或通过显式接口实现访问集合对象是线程安全的,可能需要由调用方进行同步。
一、相关的类
| 类名 | 说明 |
|---|---|
| BlockingCollection |
为实现 IProducerConsumerCollection |
| ConcurrentBag |
表示对象的线程安全的无序集合。 |
| ConcurrentDictionary<TKey,TValue> | 表示可由多个线程同时访问的键/值对的线程安全集合。 |
| ConcurrentQueue |
表示线程安全的先进先出 (FIFO) 集合。 |
| ConcurrentStack |
表示线程安全的后进先出 (LIFO) 集合。 |
| OrderablePartitioner |
表示将可排序数据源拆分为多个分区的特定方式。 |
| Partitioner | 提供针对数组、列表和可枚举项的常见分区策略。 |
| Partitioner |
表示将数据源拆分为多个分区的特定方式。 |
二、介绍2个常用的类csharp ConcurrentDictionary 和 csharp ConcurrentQueue
1、ConcurrentDictionary
2、ConcurrentQueue
属性
| 属性名 | 说明 |
|---|---|
| Count | 获取 ConcurrentQueue |
| IsEmpty | 获取一个值,该值指示 ConcurrentQueue |
| 方法 | |
| 方法名 | 说明 |
| ------ | ------ |
| Clear() | 从 ConcurrentQueue |
| CopyTo(T[], Int32) | 从指定数组索引开始将 ConcurrentQueue |
| Enqueue(T) | 将对象添加到 ConcurrentQueue |
| Equals(Object) | 确定指定对象是否等于当前对象。 (继承自 Object) |
| GetEnumerator() | 返回循环访问 ConcurrentQueue |
| GetHashCode() | 作为默认哈希函数。 (继承自 Object) |
| GetType() | 获取当前实例的 Type。 (继承自 Object) |
| MemberwiseClone() | 创建当前 Object 的浅表副本。 (继承自 Object) |
| ToArray() | 将 ConcurrentQueue |
| ToString() | 返回表示当前对象的字符串。 (继承自 Object) |
| TryDequeue(T) | 尝试移除并返回并发队列开头处的对象。 |
| TryPeek(T) | 尝试返回 ConcurrentQueue |
| 简单应用 |
更新中
参考文档:
1.微软官方文档

浙公网安备 33010602011771号