BlockingCollection

BlockingCollection 集合拥有阻塞功能。使用 生产者/消费者模式来实现并发。

using System;
using System.Collections.Concurrent;

int count = 0;
BlockingCollection<int> bc = new BlockingCollection<int>();
Task.Run(() =>
{
    while (!bc.IsCompleted)
    {
        bc.Add(count);
        count++;
        if (count > 10)
        {
            bc.CompleteAdding();
            Thread.Sleep(1);
        }
    }
}).ConfigureAwait(false);

// Customer
Task.Run(() =>
{
    // 循环删除项,直到 IsComplete=True
    foreach (var item in bc.GetConsumingEnumerable())
    {
        PrintThreadId(item.ToString());
    }
}).ConfigureAwait(false);

// 需要释放资源
bc.Dispose();

BlockingCollection 未考虑到异步访问。 如果应用程序需要异步生成者/使用者方案,考虑改用 Channel。

posted @   wesson2019  阅读(65)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2021-03-07 OSI七层协议
点击右上角即可分享
微信分享提示