在 LINQ 中并行加载图像

Pat*_*ski 3 c# linq performance asynchronous image-loading

我正在试验并行和 LINQ。看看下面的代码。它有效,但只是为了得到这个想法:

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

private Image GetImage(string path)
{
    return Image.FromFile(path);
}
Run Code Online (Sandbox Code Playgroud)

所以我基本上是从指定目录中找到的每个文件中获取图像。问题是 - 如何使这种平行?现在就像迭代它们一样。我想“以某种方式”并行化它。不知何故,因为我太缺乏经验,无法提出如何实现这一目标的想法,所以这就是为什么我问你们,伙计们,依靠一些帮助来加快速度:)

Pan*_*vos 5

使用 PLINQ:

var images=(from file in Directory.EnumerateFiles(path).AsParallel()
           select GetImage(file)).ToList();
Run Code Online (Sandbox Code Playgroud)

读取图像不受 CPU 限制,因此您可以指定更高的并行度:

var images=(from file in Directory.EnumerateFiles(path)
                                  .AsParallel()
                                  .WithDegreeOfParallelism(16)
           select GetImage(file)).ToList();
Run Code Online (Sandbox Code Playgroud)