C#实现生产消费者模式
void test()
{
int count = 0;
// 临界资源区
var queue = new BlockingCollection<string>();
// 生产者线程
Task.Factory.StartNew(() =>
{
while (true)
{
queue.Add("value" + count);
count++;
}
});
// 消费者线程1
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);
}
});
Thread.Sleep(50000);
}