C#实现生产消费者模式
2021-06-11 06:05
标签:actor str ring var blocking for 线程 int tar void test() // 消费者线程1 }); Thread.Sleep(50000); C#实现生产消费者模式 标签:actor str ring var blocking for 线程 int tar 原文地址:https://www.cnblogs.com/Llh-Forerer2015/p/10577210.html
{
int count = 0;
// 临界资源区
var queue = new BlockingCollection
// 生产者线程
Task.Factory.StartNew(() =>
{
while (true)
{
queue.Add("value" + count);
count++;
}
});
Task.Factory.StartNew(() =>
{
foreach (string value in queue.GetConsumingEnumerable())
{
Console.WriteLine("Worker 1: " + value);
}
// 消费者线程2
Task.Factory.StartNew(() =>
{
foreach (string value in queue.GetConsumingEnumerable())
{
Console.WriteLine("Worker 1: " + value);
}
});
}