using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; namespace file_finder__test; public class FileClassifier { //returns 2 seperat lists music and vidio public async Task<(List musicFiles, List videoFiles, List photoFiles)> ClassifyFilesAsync( //3 lists. all file paths and a list for vidio and music ext List allFiles, List musicExtensions, List videoExtensions, List photoExtensions) { //limit the max paralel tasks and split the total amount of files by the limit set int coreCount = Environment.ProcessorCount/2; int totalFiles = allFiles.Count; int chunkSize = (int)Math.Ceiling((double)totalFiles / coreCount); //concurrent bag instead of lists due to multi tasks var musicBag = new ConcurrentBag(); var videoBag = new ConcurrentBag(); var photoBag = new ConcurrentBag(); //a list of tasks. needed to check if all are done var tasks = new List(); for (int i = 0; i < coreCount; i++) { int start = i * chunkSize; int end = Math.Min(start + chunkSize, totalFiles); tasks.Add(Task.Run(() => { for (int j = start; j < end; j++) { string file = allFiles[j]; string ext = Path.GetExtension(file)?.ToLowerInvariant(); if (ext == null) continue; if (musicExtensions.Contains(ext)) musicBag.Add(file); else if (videoExtensions.Contains(ext)) videoBag.Add(file); else if (photoExtensions.Contains(ext)) { photoBag.Add(file); } } })); } //wait till all tasks are done and return 2 lists await Task.WhenAll(tasks); return (new List(musicBag), new List(videoBag), new List(photoBag)); } }