I have a producer consumer scenario. Producer produces data for BlockingCollection and some other thread consumes it. When consumer takes an item it must write it to a text file. There is no limit how much data can be produced by producer thread so I can't mark collection as complete. What would be the best approach to implement a consumer? My implementation:
Task.Factory.StartNew(() =>
{
try
{
using (var writer = new StreamWriter(path, true))
{
foreach (var line in _collection.GetConsumingEnumerable(token))
{
writer.WriteLine(line);
}
}
}
}, token);
The problem with this is that I keep StreamWriter open even if there is nothing inside my collection. I can put StreamWriter inside ForEach, but then I have to open and close it every time a new item arrives. And if I'm expecting thousands of items in some cases that would degrade performance.
I have read this post which describes the same problem. People suggested to use ActionBlock but it's a .NET 4.5 feature, and I'm using .NET 4.