BlockingCollection 如何实现线程安全的生产者消费者模式
使用 system.collections.concurrent.blockingcollection 是实现生产者消费者模式最推荐的方式,它内部封装了锁和条件变量,自动处理线程同步。只需实例化一个 blockingcollection,生产者通过 add() 方法放入数据,消费者通过 getconsumingenumerable() 或 take() 方法获取数据,当集合标记为完成且为空时,消费者会自动退出循环。

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
public static void Main()
{
var collection = new BlockingCollection<int>(boundedCapacity: 5);
// 启动生产者任务
Task producer = Task.Run(() =>
{
for (int i = 0; i
{
foreach (var item in collection.GetConsumingEnumerable())
{
Console.WriteLine($"Consumed: {item}");
Thread.Sleep(200); // 模拟消费耗时
}
});
Task.WaitAll(producer, consumer);
}
}</int>
运行上述代码,控制台将交替输出生产和消费的消息。由于设置了 boundedCapacity: 5,当缓冲区满时,生产者的 Add() 调用会阻塞,直到有空间为止;当所有生产者完成添加且缓冲区为空时,消费者的 GetConsumingEnumerable() 迭代器会结束,从而安全退出。
Channel 在 .NET Core 3.0+ 中的高性能实现
在 .NET Core 3.0 及更高版本中,System.Threading.Channels.Channel 提供了更现代、更灵活的生产者消费者实现,特别适合高吞吐场景。它支持异步操作,避免了线程阻塞带来的上下文切换开销,并且可以通过 BoundedChannelFullMode 配置缓冲区满时的行为(如丢弃、等待或拒绝)。

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Channels;
public class Program
{
public static async Task Main()
{
var channel = Channel.CreateBounded<int>(new BoundedChannelOptions(5)
{
FullMode = BoundedChannelFullMode.Wait // 满时等待
});
var producerTask = Task.Run(async () =>
{
for (int i = 0; i
{
await foreach (var item in channel.Reader.ReadAllAsync())
{
Console.WriteLine($"Consumed: {item}");
Thread.Sleep(200);
}
});
await Task.WhenAll(producerTask, consumerTask);
}
}</int>
该程序同样会产生生产和消费的日志。与 BlockingCollection 不同,这里使用了 async/await 模式,WriteAsync 和 ReadAllAsync 都是异步方法,不会阻塞工作线程。当缓冲区满时,生产者会挂起等待空间释放,而不是直接阻塞线程,这在 I/O 密集型或高并发场景中性能更优。
缓冲区满时 BoundedChannelFullMode.Wait 的具体行为验证
当使用 Channel.CreateBounded 并设置 FullMode = BoundedChannelFullMode.Wait 时,如果缓冲区已满,生产者调用 WriteAsync 会挂起当前任务,直到消费者取出元素腾出空间。这确保了数据不会丢失,但可能会增加生产者的延迟。
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Channels;
public class Program
{
public static async Task Main()
{
var channel = Channel.CreateBounded<int>(new BoundedChannelOptions(2)
{
FullMode = BoundedChannelFullMode.Wait
});
var producerTask = Task.Run(async () =>
{
for (int i = 0; i
{
await foreach (var item in channel.Reader.ReadAllAsync())
{
Console.WriteLine($"Consumed: {item}");
Thread.Sleep(500); // 慢速消费
}
});
await Task.WhenAll(producerTask, consumerTask);
}
}</int>
运行此代码,可以看到前两个元素快速生产,随后生产者会因为缓冲区满而等待约 500ms 直到消费者取出第一个元素。这种机制保证了数据的完整性,适用于对数据不丢失要求严格的场景。











