In C# Using Directory.GetFiles(), is there a way to start threads as files are found?
The behavior appears to be ‘find all the files’ then do what you need on each. Is there another class that allows one to start threads (up to a certain count) as files are found?
You need to call
Directory.EnumerateFiles, which is new to .Net 4.0.This method returns a lazy enumerable; each time you call
MoveNext(), it will query the filesystem for the next file.You can start your threads like this:
The temporary variable is necessary to ensure that each delegate closure references a separate variable; otherwise, they would all share the same value, causing trouble.