I have a BlockingCollection
in C# and I want to add some int
values in that collection simultaneously. Then in the consumer which is in another task I need to increase the value of the element. Then read new values but it does not work.
For example:
Add 1 To 5 to the collection.
And then in consumer one number increase it.
Result which I would like is this:
1 turns into 2.
2 turns into 3.
...
But the result is different. Here is my result:
6
6
6
6
Below is my code:
var bCollection = new BlockingCollection<int>();
var tasks = new List<Task>();
for (int i = 0; i < 5; i++)
{
tasks.Add(Task.Run(async () =>
{
bCollection.Add(i);
}));
}
var completeTask = Task.WhenAll(tasks).ContinueWith(t => bCollection.CompleteAdding());
int k = 0;
Task consumer = Task.Run(() =>
{
while (!bCollection.IsCompleted)
{
if (bCollection.TryTake(out int i))
{
i=i+1; // add one number
global::System.Console.WriteLine(i);
k++;
}
}
});
var allTasks = new List<Task>(tasks);
allTasks.Add(consumer);
allTasks.Add(completeTask);
await Task.WhenAll(allTasks);