obsidian/笔记文件/2.笔记/ConcurrentQueue.md
2025-03-26 00:02:56 +08:00

99 lines
2.6 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#unity/日常积累
# ConcurrentQueue 类
- 参考
反馈
[](https://learn.microsoft.com/zh-cn/dotnet/api/system.collections.concurrent.concurrentqueue-1?view=net-8.0#definition)
## 定义
命名空间:
[System.Collections.Concurrent](https://learn.microsoft.com/zh-cn/dotnet/api/system.collections.concurrent?view=net-8.0)
程序集:
System.Collections.Concurrent.dll
表示线程安全的先进先出 (FIFO) 集合。
``` cs
public class ConcurrentQueue<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection
```
#### 类型参数
T
队列中包含的元素的类型。
继承
[Object](https://learn.microsoft.com/zh-cn/dotnet/api/system.object?view=net-8.0)
``` cs
ConcurrentQueue<T>
```
示例
``` cs
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
class CQ_EnqueueDequeuePeek
{
// Demonstrates:
// ConcurrentQueue<T>.Enqueue()
// ConcurrentQueue<T>.TryPeek()
// ConcurrentQueue<T>.TryDequeue()
static void Main ()
{
// Construct a ConcurrentQueue.
ConcurrentQueue<int> cq = new ConcurrentQueue<int>();
// Populate the queue.
for (int i = 0; i < 10000; i++)
{
cq.Enqueue(i);
}
// Peek at the first element.
int result;
if (!cq.TryPeek(out result))
{
Console.WriteLine("CQ: TryPeek failed when it should have succeeded");
}
else if (result != 0)
{
Console.WriteLine("CQ: Expected TryPeek result of 0, got {0}", result);
}
int outerSum = 0;
// An action to consume the ConcurrentQueue.
Action action = () =>
{
int localSum = 0;
int localValue;
while (cq.TryDequeue(out localValue)) localSum += localValue;
Interlocked.Add(ref outerSum, localSum);
};
// Start 4 concurrent consuming actions.
Parallel.Invoke(action, action, action, action);
Console.WriteLine("outerSum = {0}, should be 49995000", outerSum);
}
}
```
## 注解
 备注
[ConcurrentQueue<T>](https://learn.microsoft.com/zh-cn/dotnet/api/system.collections.concurrent.concurrentqueue-1?view=net-8.0)[IReadOnlyCollection<T>](https://learn.microsoft.com/zh-cn/dotnet/api/system.collections.generic.ireadonlycollection-1?view=net-8.0)实现从 .NET Framework 4.6 开始的接口;在.NET Framework的早期版本中[ConcurrentQueue<T>](https://learn.microsoft.com/zh-cn/dotnet/api/system.collections.concurrent.concurrentqueue-1?view=net-8.0)类未实现此接口。