Answer the question
In order to leave comments, you need to log in
C# How to implement multi-threaded search for files across all drives?
Hello, I have the following code:
public void SearchFile(string FileLocation)
{
// Расширения изображений
var Extensions = new[]
{
".jpg", ".png"
};
string[] files = Directory.GetFiles(FileLocation);
string[] Directories = Directory.GetDirectories(FileLocation);
for (int i = 0; i < files.Length; i++)
{
string extension = Path.GetExtension(files[i]);
if (Extensions.Contains(extension))
{
// обрабатываем файл files[i]
}
}
for (int i = 0; i < Directories.Length; i++)
{
SearchFile(Directories[i]);
}
}
Answer the question
In order to leave comments, you need to log in
Try to play around with the number of threads, because. in addition to searching for files, you are also supposed to have some kind of processing, for sure the results will vary.
class Program
{
static readonly string[] Extensions = new string[] { "*.jpg", "*.png" };
static void Main(string[] args)
{
var drives = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed);
drives.AsParallel().ForAll(d =>
{
SearchFile(d.RootDirectory.FullName);
});
}
static void SearchFile(string path, int maxDegree = 1)
{
var images = Directory.GetFiles(path).Where(f =>
{
var ext = Path.GetExtension(f);
return Extensions.Any(e => e.Equals(ext, StringComparison.OrdinalIgnoreCase));
});
images.ToList().ForEach(i =>
{
// process image
});
var dirs = Directory.GetDirectories(path);
dirs.AsParallel().WithDegreeOfParallelism(maxDegree).ForAll(d => SearchFile(d));
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question