Parallel loading images in LINQ

本小妞迷上赌 提交于 2019-12-07 17:55:42

问题


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 :)


回答1:


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();



回答2:


You could do something like

var images = new ConcurrentBag<Image>();

Parallel.ForEach(Directory.GetFiles(path)
.Select(f => new { img = GetImage(f) })
.Select(x => x.img), img => images.Add(img));


来源:https://stackoverflow.com/questions/28884090/parallel-loading-images-in-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!