Skip to main content

BlockingCollection

  • BlockingCollection

class Program
{
static BlockingCollection<string> cakeOrders = new BlockingCollection<string>(boundedCapacity: 5);

static void Baker()
{
foreach (var order in cakeOrders.GetConsumingEnumerable())
{
Console.WriteLine($"Baker is baking {order}...");
Thread.Sleep(2000); // Simulate baking time
Console.WriteLine($"Baker has finished baking {order}");
}
}

static void Main()
{
Task.Run(Baker); // Start the baker task

// Simulate incoming cake orders
for (int i = 1; i <= 10; i++)
{
string order = $"Cake {i}";
cakeOrders.Add(order);
Console.WriteLine($"Order received: {order}");
Thread.Sleep(1000); // Simulate order processing time
}

// Signal that no more orders will be added
cakeOrders.CompleteAdding();

Console.ReadLine();
}
}
  • O BlockingCollection é semelhante a um funil de threads onde pode ser consumidos e publicados valores e ela controla
  • É uma implementação do padrão Producer-Consumer