csharp unsafe BitmapData 访问内存泄漏
Posted
技术标签:
【中文标题】csharp unsafe BitmapData 访问内存泄漏【英文标题】:csharp unsafe BitmapData Access Memory Leak 【发布时间】:2018-01-22 14:03:01 【问题描述】: public Point PixelSearchPoint(Bitmap b, Color PixelColor, int Shade_Variation)
Color Pixel_Color = PixelColor;
Point Pixel_Coords = new Point(-1, -1);
using (Bitmap RegionIn_Bitmap = (Bitmap)b.Clone())
BitmapData RegionIn_BitmapData = RegionIn_Bitmap.LockBits(new Rectangle(0, 0, RegionIn_Bitmap.Width, RegionIn_Bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
int[] Formatted_Color = new int[3] Pixel_Color.B, Pixel_Color.G, Pixel_Color.R ; //bgr
unsafe
for (int y = 0; y < RegionIn_BitmapData.Height; y++)
byte* row = (byte*)RegionIn_BitmapData.Scan0 + (y * RegionIn_BitmapData.Stride);
for (int x = 0; x < RegionIn_BitmapData.Width; x++)
if (row[x * 3] >= (Formatted_Color[0] - Shade_Variation) & row[x * 3] <= (Formatted_Color[0] + Shade_Variation)) //blue
if (row[(x * 3) + 1] >= (Formatted_Color[1] - Shade_Variation) & row[(x * 3) + 1] <= (Formatted_Color[1] + Shade_Variation)) //green
if (row[(x * 3) + 2] >= (Formatted_Color[2] - Shade_Variation) & row[(x * 3) + 2] <= (Formatted_Color[2] + Shade_Variation)) //red
Pixel_Coords = new Point(x, y);
RegionIn_Bitmap.Dispose();
goto End;
End:
b.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
return Pixel_Coords;
此代码从位图中搜索查找颜色代码
using (Bitmap b = new Bitmap(NativeHelper.GetOriginalWinScreen(handle)))
Point p = PixelSearchPoint(b, c, 0);
if (p.X != -1 && p.Y != -1)
Logwrite(p.X + "/" + p.Y + " Click With" + c.ToString());
chk = true;
ClickPos(p.X, p.Y);
notecomplete = true;
counttest++;
b.Dispose();
当访问不安全的方法时,这段代码内存泄漏得如此之快 GC.Collect 和 GC.WaitForPendingFinalizers();不使用 UnSafe 方法??
-
使用 GDI+ Capture 和此方法不是 MemoryLeak 的原因
使用 Foreach Find Point from Color using unsafe method
【问题讨论】:
【参考方案1】:如果您调用 RegionIn_Bitmap.LockBits,您需要确保在处理之前调用 UnlockBits。
【讨论】:
Pixel_Coords = new Point(x, y); b.UnlockBits(RegionIn_BitmapData); b.Dispose(); RegionIn_Bitmap.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); goto End;
仍然不工作..以上是关于csharp unsafe BitmapData 访问内存泄漏的主要内容,如果未能解决你的问题,请参考以下文章