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);
}
});string
Thread.Sleep(50000);
}it