V
V
vladimirchelyabinskiy2016-04-27 08:06:23
C++ / C#
vladimirchelyabinskiy, 2016-04-27 08:06:23

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]);
            }
        }

What needs to be added in order for the program to search for images on all disks, multithreaded, or at least use parallel.for

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Iron Bug, 2016-04-27
@vladimirchelyabinskiy

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 question

Ask a Question

731 491 924 answers to any question