2017-10-15 185 views
1

我正在使用Parallel.For循环来处理一些图像。当我尝试保存图像,有时我得到了GDI发生exception-图像无法保存在Parallel.For循环

一般性错误+

一些图像得到保存,然后保存一些文件后,该异常来随机。

  • 我试图分配原来的位图图像对象到不同的位图图像,然后将其保存
  • 使用Monitor.Enter保存文件

下面之间进行同步尝试是我的代码 -

Parallel.For(0, 14, cnt => 
{ 
    using (Bitmap originalImage = (Bitmap)Bitmap.FromFile(@imagePath)) 
    { 
     for (int i = 0; i < originalImage.Width; i++) 
     { 
      for (int x = 0; x < originalImage.Height; x++) 
      { 
       System.Drawing.Color oc = originalImage.GetPixel(i, x); 
       int gray = (int)((oc.R * 0.3) + (oc.G * 0.59) + (oc.B * 0.11)); 
       System.Drawing.Color nc = System.Drawing.Color.FromArgb(oc.A, gray, gray, gray); 
       originalImage.SetPixel(i, x, nc); 
      } 
     } 
     try 
     { 
      //Bitmap grayscaleImage = originalImage; 
      //grayscaleImage.Save(@processesImagesPath + DateTime.Now.ToString("dd-MM-yyyy_hh.mm.ss") + ".jpg"); //line of exception 

      //above lines did not work 

      Monitor.Enter(originalImage); 
      originalImage.Save(@processesImagesPath + DateTime.Now.ToString("dd-MM-yyyy_hh.mm.ss") + ".jpg"); //line of exception 
     } 
     finally 
     { 
      Monitor.Exit(originalImage); 
     } 
    } 
}); 
+0

'imagePath'总是在'Parallel.For'一样吗? – Backs

+0

@返回没有。抱歉。我更新了代码,现在检查。 –

+0

我没有看到'cnt'变量的使用。看起来,你试图并行更新一个文件14次 – Backs

回答

1

DateTime.Now.ToString("dd-MM-yyyy_hh.mm.ss") - 两个图像可以在一秒内保存,你会得到一个错误。创建更多独特的文件名 例如:

var filename = DateTime.Now.ToString("dd-MM-yyyy_hh.mm.ss") + cnt