0

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);
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
  • Or is it just codereview and you want a thumbs up/down? If yes https://codereview.stackexchange.com/ – Rand Random Jan 14 '23 at 10:11
  • for example: add 1 To 5 to the collection. and then in consumer one number increment it. result would be like this: 1 turns into 2. 2 turns into 3. – shirin monzavi Jan 14 '23 at 10:19
  • 2
    Your first loop is using [a modified closure](https://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/) which likely will result in a value of `6` being passed to all the tasks (because the value of `i` will become `6` at the end of the loop). Fix this by introducing a new variable `int j = i;` inside the loop and then pass that to `bCollection.Add(j);` – Matthew Watson Jan 14 '23 at 10:40
  • As a side note the consuming pattern is incorrect. The right way is to use the `GetConsumingEnumerable` method. See [this answer](https://stackoverflow.com/questions/75058581/net-6-consoleapp-multiple-blockingcollectiont-huge-cpu-consumption/75061965#75061965) for an example. – Theodor Zoulias Jan 14 '23 at 13:02

0 Answers0