First and foremost: make a local copy of the path and pass that into the thread instead of the for-loop variable. Closing over the loop variable is considered harmful.
I don't know why you get an index out of range exception, but you can also avoid that by using a foreach
-loop.
//get the languages from the folders
string[] filePaths = Directory.GetDirectories(rootDirectory);
foreach(string filePath in filePaths)
{
Console.WriteLine(filePath.Split('\\').Last());
string tmpPath = filePath; // <-- local copy
//go through files in each folder and sub-folder with threads
Thread t1 = new Thread(() => new HBScanner(new DirectoryInfo(tmpPath)).HBscan());
t1.Start();
threads.Add(t1);
}
Second: use Join
on the threads instead of having some custom wait code.
// wait for all threads to complete before proceeding
foreach (Thread thread in threads)
{
thread.Join();
}
Finally, make sure that there is no contention on the database. Without further information on what the HBScanner
does, it's difficult to say anything else about what might be causing this issue.