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(() =>
{
    foreach (var item in bc.GetConsumingEnumerable())
    {
        PrintThreadId(item.ToString());
    }
}).ConfigureAwait(false);

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

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

posted @ 2023-03-07 15:44  wesson2019  阅读(62)  评论(0编辑  收藏  举报