Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created May 22, 2015 18:45
Show Gist options
  • Save vlad-bezden/8421d8e3ac6e592a5722 to your computer and use it in GitHub Desktop.
Save vlad-bezden/8421d8e3ac6e592a5722 to your computer and use it in GitHub Desktop.
Producer/Consumer example using asynchronous blocking queue. This example has 10 producers and 1 consumer. BufferBlock<T> is in the Microsoft.Tpl.Dataflow NuGet package
private BufferBlock<int> queue = new BufferBlock<int>();
void Main()
{
var producers = Enumerable.Range(0, 10).Select(async x =>
{
await Producer();
});
var consumer = Consumer();
Task.WaitAll(producers.ToArray());
consumer.Wait();
Console.WriteLine("Done");
}
private async Task Producer()
{
var data = Enumerable.Range(1, 5);
foreach (var item in data)
{
await Task.Delay(TimeSpan.FromSeconds(1));
await queue.SendAsync(item);
Console.WriteLine("Producer. Item: {0}, TimeStamp: {1}", item, DateTime.Now);
}
queue.Complete();
return;
}
private async Task Consumer()
{
while (await queue.OutputAvailableAsync())
{
var item = await queue.ReceiveAsync();
Console.WriteLine("Consumer. Item: {0}, TimeStamp: {1}", item, DateTime.Now);
}
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment