Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel loading images in LINQ

I am experimenting with parallel and LINQ. Look at the code below. It works, but just to get the idea:

private void LoadImages(string path)
{
    images =
        Directory.GetFiles(path)
        .Select(f => GetImage(f))
        .ToList();
}

private Image GetImage(string path)
{
    return Image.FromFile(path);
}

So I am basically getting an image from each file found in the specified directory. The question is - how to make this parallel? Right now it is like iterating over them. I would like to parallelize it "somehow". Somehow, because I am too inexperienced to suggest an idea how to achieve this, so that's why I am asking you, guys, counting on some help to make this faster :)

like image 479
Patryk Golebiowski Avatar asked Feb 02 '26 16:02

Patryk Golebiowski


1 Answers

Using PLINQ:

var images=(from file in Directory.EnumerateFiles(path).AsParallel()
           select GetImage(file)).ToList();

Reading the images isn't CPU bound, so you can specify a higher degree of parallelism:

var images=(from file in Directory.EnumerateFiles(path)
                                  .AsParallel()
                                  .WithDegreeOfParallelism(16)
           select GetImage(file)).ToList();
like image 110
Panagiotis Kanavos Avatar answered Feb 04 '26 07:02

Panagiotis Kanavos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!