This is a follow up question to Use ThreadPool in C# within a loop and wait for all threads to finish and Save the content of several csv files into a searchable array C#
I have a code that looks like this:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ThreadPooling
{
class Program
{
static void Main(string[] args)
{
var FolderNames= new List<(string name)>()
{
"folder1",
"folder2"
}
var tasks = new List<Task>();
foreach (var folder in FolderNames)
{
Console.WriteLine("Staring process" + folder.name + "...");
var task = Task.Run(() => Job(folder.name));
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
Console.WriteLine("All calculations done.");
Console.WriteLine("\nPress any key to exit the program...");
Console.ReadKey();
}
public class Job()
{
public Job(folder)
{
CsvFile File = new CsvFile();
File.OpenCsvFiles(folder); //opens all csv files within the folder
}
}
public class CsvFile
{
string folder;
static Dictionary<string, Dictionary<int, Dictionary<int, string>>> _dictionary =
new Dictionary<string, Dictionary<int, Dictionary<int, string>>>();
public void OpenCsvFiles(string folder) //opens all the csv files in the output folder and saves their's content to a Dictionary
{
this.folder = folder;
foreach (string path in Directory.GetFiles(folder, "*.csv")) // fileName is the file name WITH its full path
{
try
{
string[][] m_Data = File
.ReadLines(path)
.Where(line => !string.IsNullOrWhiteSpace(line))
//.Skip(1) //skipping the headers
.Select(line => line.Split(','))
.ToArray();
PopulateDictionary(Path.GetFileName(path), m_Data); //fills the Dictionary with each file
}
catch (Exception ex)
{
MessageBox.Show("Error in OpenCsvFiles (" + path + ") : " + ex.Message);
}
}
}
static void PopulateDictionary(string filename, string[][] data)
{
_dictionary.Add(filename, new Dictionary<int, Dictionary<int, string>>());
for (int i = 0; i < data.Length; i++)
{
_dictionary[filename].Add(i, new Dictionary<int, string>());
for (int j = 0; j < data[i].Length; j++)
{
_dictionary[filename][i].Add(j, data[i][j]);
}
}
}
}
}
}
What I want to be able to do is to loop a list of folders, open all .csv files in each of the folders and save the values to a dictionary in CsvFile
accessible to each Process
that is run parallel. However, I run into the problem that C#, unlike C++, does not seem to create separate class objects of CsvFile
within Process
. That is, if I run into a file with the same file name in folder1 and folder2, say file Alpha.csv, I get an error that the code tires to add the same key, Alpha, twice to the dictionary.
But I want the dictionaries in CsvFile
to be created and used separately with in each class object of Process
, not one CsvFile
object to be created and then used by all Process
classes parallel. Is this possible?