0

I've been trying to get familiar with the Tasks library in C# and parallelism in general. My newMethodForThreads() method gives an error indicating the the thread is trying to access a file already opened by another thread.

In trying to debug this, it seems that the for loop in createTasks() is passing in the same arguments into newMethodForThreads() in different iterations. It also seems that some iterations of i don't get passed into the task either, and are skipped entirely. Does anyone understand what's going on?

public static List<Task> createTasks(int x)
{

    List<Task> taskList = new List<Task>();

    for (int i = 1; i <= x; i++)
    {
        taskList.Add(Task.Factory.StartNew(() => newMethodForThreads(i)));
    }

    return taskList;
}


public static void newMethodForThreads(int i)
{
    File.WriteAllLines($"C:\\Users\\my_username\\Desktop\\Shenanigans\\Threadedfile{i}.txt", list);
    Console.WriteLine($"File Threadedfile{i}.txt finished.");
}
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77

1 Answers1

-1

The problem is that the task has a reference to the integer. So it will use the value the integer has when the taks is started and not when the taks is created.

To fix it assign the integer to a local variable just before the task is created.

        for (int i = 1; i <= x; i++)
        {
           var localValue = i;
           taskList.Add(Task.Factory.StartNew(() => newMethodForThreads(localValue)));
        }
gjhommersom
  • 159
  • 1
  • 7