在 LINQ 中并行加载图像
Parallel loading images in LINQ
我正在试验并行和 LINQ。看看下面的代码。它有效,但只是为了理解:
private void LoadImages(string path)
{
images =
Directory.GetFiles(path)
.Select(f => GetImage(f))
.ToList();
}
private Image GetImage(string path)
{
return Image.FromFile(path);
}
所以我基本上是从指定目录中找到的每个文件获取图像。问题是 - 如何使这种平行?现在就像迭代它们一样。我想将它并行化 "somehow"。不知何故,因为我太缺乏经验,无法提出如何实现这一点的想法,所以这就是为什么我要问你们,伙计们,希望得到一些帮助来加快速度:)
你可以这样做
var images = new ConcurrentBag<Image>();
Parallel.ForEach(Directory.GetFiles(path)
.Select(f => new { img = GetImage(f) })
.Select(x => x.img), img => images.Add(img));
使用 PLINQ:
var images=(from file in Directory.EnumerateFiles(path).AsParallel()
select GetImage(file)).ToList();
读取图像不受 CPU 限制,因此您可以指定更高的并行度:
var images=(from file in Directory.EnumerateFiles(path)
.AsParallel()
.WithDegreeOfParallelism(16)
select GetImage(file)).ToList();
我正在试验并行和 LINQ。看看下面的代码。它有效,但只是为了理解:
private void LoadImages(string path)
{
images =
Directory.GetFiles(path)
.Select(f => GetImage(f))
.ToList();
}
private Image GetImage(string path)
{
return Image.FromFile(path);
}
所以我基本上是从指定目录中找到的每个文件获取图像。问题是 - 如何使这种平行?现在就像迭代它们一样。我想将它并行化 "somehow"。不知何故,因为我太缺乏经验,无法提出如何实现这一点的想法,所以这就是为什么我要问你们,伙计们,希望得到一些帮助来加快速度:)
你可以这样做
var images = new ConcurrentBag<Image>();
Parallel.ForEach(Directory.GetFiles(path)
.Select(f => new { img = GetImage(f) })
.Select(x => x.img), img => images.Add(img));
使用 PLINQ:
var images=(from file in Directory.EnumerateFiles(path).AsParallel()
select GetImage(file)).ToList();
读取图像不受 CPU 限制,因此您可以指定更高的并行度:
var images=(from file in Directory.EnumerateFiles(path)
.AsParallel()
.WithDegreeOfParallelism(16)
select GetImage(file)).ToList();