For a while I have been interested in seeing if some tasks work well when split across multiple threads.
On the one project I have been busy with I have been creating a lot of small utility apps, to do single tasks for me, so this morning while modifying one I thought I would give it a try.
What I wrote seems to work, although I am not sure if it is the best way, or recommended way to do something like this, so I want to ask what is wrong with my code and how could it be done better. What it is doing is not really important, and I am not interested if this sort of task should be split up, but more along the lines of how good or bad is the code that I have written.
private static void ExportDocTypes(IEnumerable<string> docTypes)
{
var queue = new Queue<string>(docTypes);
var tasks = new List<Task>();
for (byte i = 0; i < threadCount; i++) //threadCount is a const set to 4.
{
Action a = () =>
{
while(queue.Count() > 0) {
var type = queue.Dequeue();
ExportDocuments(type, i); //i is only sent for response.write
}
};
var t = new Task(a);
t.Start();
tasks.Add(t);
System.Threading.Thread.Sleep(10);
}
while (tasks.Count() > 0)
{
foreach (var t in tasks)
{
if (t.IsCompleted)
{
t.Dispose();
tasks.Remove(t);
}
}
System.Threading.Thread.Sleep(1000);
}
}
break
from the foreach loop, butTask.WaitAll()
or even linq.All(t => t.IsCompleted)
would be more elegant. \$\endgroup\$