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.
Using QueueUserWorkItem() is the low level, barebones approach. With no control over your jobs, it's fire and forget.
Tasks run on top of the ThreadPool, andasync/awaitcan solve your problem here.The toplevel:
and then you Search() becomes
That DoTheJob() thing should idealy use async I/O but otherwise you can
await Task.Run( () => DoTheJob(f))