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.");
}