每个循环的并行不会保存所有文件

时间:2017-11-08 11:04:46

标签: c# parallel-processing parallel-foreach

我在图像转换器上写字。当我使用并行时,并非所有图像都被保存。在磁盘上写文件的处理速度是否过快?

这是我的代码:

private void convert()
{
    Parallel.ForEach(source.GetFiles("*.tif"), 
         new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount }, 
         file =>
         {                  
            fileName = file.Name;
            MagickImage image = new MagickImage(sourceFolderPath + "\\" + file);
            image.ColorSpace = ColorSpace.XYZ;
            image.GammaCorrect(2.4);
            image.Write(destinationFolderPath + "\\" + fileName);
         });
}

我做错了什么?

1 个答案:

答案 0 :(得分:3)

尝试处置image

private void convert()
{
    Parallel.ForEach(source.GetFiles("*.tif"), 
         new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount }, 
         file =>
         {                  
            fileName = file.Name;
            using (MagickImage image = new MagickImage(sourceFolderPath + "\\" + file))
            {
                image.ColorSpace = ColorSpace.XYZ;
                image.GammaCorrect(2.4);
                image.Write(destinationFolderPath + "\\" + fileName);
            }
         });
}