Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created May 22, 2015 14:54
Show Gist options
  • Save vlad-bezden/4b772d89fc6ce937f866 to your computer and use it in GitHub Desktop.
Save vlad-bezden/4b772d89fc6ce937f866 to your computer and use it in GitHub Desktop.
Example of Producer/Consumer using BlockingCollection
private readonly BlockingCollection<int> _blockingQueue = new BlockingCollection<int>();
void Main()
{
var producer = Producer();
var consumer = Consumer();
Task.WaitAll(producer, consumer);
Console.WriteLine("Done");
}
private Task Producer()
{
var data = Enumerable.Range(1, 5);
return Task.Run(async () =>
{
foreach (var x in data)
{
await Task.Delay(TimeSpan.FromSeconds(1));
Console.WriteLine(string.Format("Producer. Value = {0}. TimeStamp = {1}", x, DateTime.Now));
_blockingQueue.Add(x);
}
_blockingQueue.CompleteAdding();
});
}
private Task Consumer()
{
return Task.Run(() =>
{
foreach (var x in _blockingQueue.GetConsumingEnumerable())
{
Console.WriteLine(string.Format("Consumer: Value = {0}. TimeStamp = {1}", x, DateTime.Now));
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment