I'm working on a console application written in c#
The purpose of this app is to go through all drives and files and do something on them. But going through all files with a single thread is a time consuming process which is not my goal.
So I decided to use ThreadPool
to handle it like so :
class Program () {
static void Main(string[] args) {
foreach (var d in DriveInfo.GetDrives()) {
ThreadPool.QueueUserWorkItem(x => Search(d.RootDirectory.GetDirectories()));
}
Console.WriteLine("Job is done.");
Console.ReadKey();
}
private static void Search(DirectoryInfo[] dirs) {
foreach (var dir in dirs) {
try {
foreach (var f in dir.GetFiles()) {
ThreadPool.QueueUserWorkItem(x => DoTheJob(f));
}
ThreadPool.QueueUserWorkItem(x => Search(dir.GetDirectories()));
} catch (Exception ex) {
continue;
}
}
}
}
The problem is Console.WriteLine("Job is done.")
executes before all threads get done. I've read some questions and answers but none of them addressed my problem.
How can I call a method after all threads in the ThreadPool
finished their job?
Note: As you might know, I have no idea how many threads will be created because I don't know how many files are there. And setting timeout is not an option.
Here is example of how you can use
Parallel.ForEach
to produce fair load:If however
DoTheJob
contains I/O-bound operations I'd consider to handle it withawait
as Henk Holterman suggested asParallel.ForEach
is agnostic for I/O load.