60 lines
2.2 KiB
C#
60 lines
2.2 KiB
C#
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<string> musicFiles, List<string> videoFiles, List<string> photoFiles)> ClassifyFilesAsync(
|
|
//3 lists. all file paths and a list for vidio and music ext
|
|
List<string> allFiles,
|
|
List<string> musicExtensions,
|
|
List<string> videoExtensions,
|
|
List<string> 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<string>();
|
|
var videoBag = new ConcurrentBag<string>();
|
|
var photoBag = new ConcurrentBag<string>();
|
|
//a list of tasks. needed to check if all are done
|
|
var tasks = new List<Task>();
|
|
|
|
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<string>(musicBag), new List<string>(videoBag), new List<string>(photoBag));
|
|
}
|
|
} |