Created
May 22, 2015 14:54
-
-
Save vlad-bezden/4b772d89fc6ce937f866 to your computer and use it in GitHub Desktop.
Example of Producer/Consumer using BlockingCollection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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