C#自带生产者消费者的集合
in 默认分类 with 0 comment

记录一下C#自带的生产者和消费者集合 BlockingCollection

var collection = new BlockingCollection<string>(boundedCapacity: 1);

// 消费者
Task.Run(() => {
    foreach (var item in collection.GetConsumingEnumerable()) {
        Console.WriteLine($"出队 {item}");
        Thread.Sleep(1000);
    }
});

Task.Run(() => {
    while (true) {
        //collection.Count == 0是为了写入 如果有写入就先不轮询
        if (collection.Count == 0) {
            collection.Add("轮询");
        }
        Thread.Sleep(500);
    }
});

while (true) {
    Console.ReadLine();
    collection.Add("写入");
}