0

I am trying to do add values after a specific node.Each task should add a value from a given list by index. For example: the list contains 2 numbers {1,10} i want to add 6 values after the 10, so it will look like {1,10,11,12,13,14,15,16}. The problem is that it adds the last value N amount of times and the result is {1,10,16,16,16,16,16,16}.

static async Task<LinkedList<int>> ParrallelInsertion(List<int> values, LinkedList<int> list)
    {
        var tasks = new List<Task>();

        for (int i = 0; i < values.Count-1; i++)
        {
            tasks.Add(Task.Run(
                () =>
                {
                    lock (list)
                    {
                        var node = list.Find(10);
                        if (node == null)
                        {
                            list.AddLast(values[i]);
                        }
                        else
                        {
                            list.AddAfter(node, values[i]);
                        }
                    }
                }
                ));
        }

        await Task.WhenAll(tasks);
        return list;
    }
Andrea
  • 247
  • 2
  • 4
  • 14

1 Answers1

0

I think that moving the entire Task.RunCode (including the call to Task.Run) to a dedicated method should solve the problem and call that method for each iteration of the loop.

Hope it helps!

Itay Podhajcer
  • 2,616
  • 2
  • 9
  • 14