Your current code may go wrong if a combination of the following two is executed:
- there are a lot of files.
- file processing (DoStuff) takes a considerable amount of time
Threadpool does not have enough capacity to balance the load and will create more and more threads that go beyond the optimal number.
If you can use Fx4, use TPL.
For earlier versions, rewrite your code to use fewer threads.
Edit since you are using Fx4:
The biggest gain may be to use System.Directory.EnumFiles() to replace Directory.GetFiles() .
Sketch:
var files = System.Directory.EnumerateFiles(...); // deferred execution Parallel.ForEach(files, f => DoStuff(f)); // maybe use MaxDegree or CancelationToken // all files done here
You can also wrap this. ForEach in one (one) try / catch, etc.
And if DoStuff() requires parallelism, you should also use TPL, perhaps go through a CancellationToken, etc. He would put all parallelism under the control of one scheduler.
You may need help fine-tuning, but it will also be much easier than without TPL.
source share