我是 c# 和并行处理的新手。我正在尝试处理一堆图像,我已经编写了处理方法。我在 imagelist 上添加了并行 foreach 循环,如下所示
Parallel.ForEach(Directory.GetFiles(path), new ParallelOptions { MaxDegreeOfParallelism = 2 }, fileName =>
{
List<string> tempList = new List<string>();
using (Bitmap imageBitmap= new Bitmap(fileName))
{
using (ImageProcessor imageProcessor= new ImageProcessor ())
{
tempList = imageProcessor.ProcessImage(imageBitmap);
}
}
if (tempList.Count != 0)
allElements.Add(tempList.FirstOrDefault());
});
在其中一种方法中,我使用该LockBits
方法获取BitMapData
图像并将该数据复制到byte[]
但是方法抛出异常,方法代码是
private byte[] ImageToByteArray(Bitmap b, out int stride)
{
object sync = new object();
BitmapData bd;
lock (sync)
{
Rectangle rect = new Rectangle(0, 0, b.Width, b.Height);
bd = b.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);//This line throwing the exception.
try
{
byte[] pxl = new byte[bd.Stride * b.Height];
Marshal.Copy(bd.Scan0, pxl, 0, bd.Stride * b.Height);
stride = bd.Stride;
return pxl;
}
finally
{
b.UnlockBits(bd);
}
}
}
我尝试lock
了使用该LockBits
方法的代码,因此一次只有一个线程使用该代码,因此一次使用内存。
我还尝试使用lock
父方法中的方法的 with 调用,例如
public List<string> ProcessImage(BitMap image)
{
object sync = new object();
int stride;
byte[] rawImg;
using (image)
{
lock (sync)
{
rawImg = ImageToByteArray(image, out stride);
}
processingImg = new ProcessImage(rawImg, image.Width, image.Height);
}
}
但仍然有例外。异常没有给我任何堆栈跟踪或解释,只有我得到的异常消息是Out Of Memory
。
我遇到了这个答案,当我减少它时MaximumDegreeOfParallelism
它工作正常。
所以基本上我想知道,1)为什么即使代码上Out Of Memory
有2个线程,代码也会抛出异常lock
?2)如果我增加,是否有可能避免这个异常DegreeOfParallelism
?任何帮助都会很棒。
如有任何混淆,请随时发表评论。