问题
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