My program has a list of 200k files. I have to import each to the database. I takes a long time so I started researching about multithreads as a means to speed up the importing process. I finally got to an implementation but I'm not sure it's actually working.
After using http://stackoverflow.com/questions/2702545/workaround-for-the-waithandle-waitall-64-handle-limit as a sample for my c# code I've came up with:
int threadCount = 0;
for (int i = 0; i < this.Total; i++)
{
Finished = new ManualResetEvent(false);
threadCount = this.ThreadCount;
Interlocked.Increment(ref threadCount);
FileHandler fh = new FileHandler(finished, sorted[i], this.PicturesFeatures, this.Outcome, this.SiteIds, this.LastId, this.Order, this.ThreadCount);
Console.Write(i + " ");
ThreadPool.QueueUserWorkItem(new WaitCallback(HandleFile), fh);
Console.Write(i + " ");
Finished.WaitOne();
}
And HandleFile() goes as:
private void HandleFile(object s)
{
try
{
//code
}
finally
{
if (Interlocked.Decrement(ref threadCount) == 0)
{
Finished.Set();
}
}
}
I've put those console.Write thinking that if a process is longer it would finish later than some other ("0 0 1 2 2 1 3 3 ..."), but it's always in order ("0 0 1 1 2 2 3 3 4 4 ...")