From 609344d976d311d8b7b16b2f1aeecf5b4a154c75 Mon Sep 17 00:00:00 2001 From: Joseph Chen Date: Thu, 30 May 2024 11:06:59 +0800 Subject: [PATCH] Filter files before processing in parallel --- Program.cs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Program.cs b/Program.cs index 9d32f2d..fb8938a 100644 --- a/Program.cs +++ b/Program.cs @@ -54,16 +54,16 @@ private static void ProcessDir(string directoryPath, HashSet allowed_ext { Console.WriteLine($"Processing directory: {directoryPath}"); - Parallel.ForEach(Directory.EnumerateFiles(directoryPath, "*", SearchOption.AllDirectories), file_path => + var files = Directory.EnumerateFiles(directoryPath, "*", SearchOption.AllDirectories) + .AsParallel() + .Where(file_path => allowed_exts.Contains(Path.GetExtension(file_path).ToLower())); + + Parallel.ForEach(files, file_path => { - string file_ext = Path.GetExtension(file_path).ToLower(); - if (allowed_exts.Contains(file_ext)) - { - RemoveTrailingBlanks(file_path); - sem.Wait(); - Console.WriteLine(Path.GetRelativePath(directoryPath, file_path)); - sem.Release(); - } + RemoveTrailingBlanks(file_path); + sem.Wait(); + Console.WriteLine(Path.GetRelativePath(directoryPath, file_path)); + sem.Release(); }); }