C#通过函数创建一个Bitmap对象,以下是我使用的两个函数,在垃圾回收上都有问题,请大家帮我改进。 public Bitmap RetABitmap1()
{
int width = 2000;
int height = 2000;
int stride = (int)((width * 24 + 31) & 0xFFFFFFE0)/ 8; int dataSize = width * height;
byte [] data = new byte [dataSize]; //这个方法的问题是,
System.IntPtr scan0 = System.Runtime.InteropServices.Marshal.AllocHGlobal(dataSize);
System.Runtime.InteropServices.Marshal.Copy(data, 0, scan0, dataSize - 1);
return new System.Drawing.Bitmap(width, height, stride, System.Drawing.Imaging.PixelFormat.Format24bppRgb, scan0); } public Bitmap RetABitmap2()
{
int width = 2000;
int height = 2000;
int stride = (int)((width * 24 + 31) & 0xFFFFFFE0)/ 8; int dataSize = width * height;
byte [] data = new byte [dataSize]; unsafe
{
fixed(byte* pData = &data[0]) 
{
IntPtr scan0 = new IntPtr(pData); 
return new System.Drawing.Bitmap(width, height, stride, System.Drawing.Imaging.PixelFormat.Format24bppRgb, scan0);
}
} }随便创建一个窗口添加按钮分别多次调用以上代码
private void button1_Click(object sender, System.EventArgs e)
{
for(int i = 0; i < 10; i++)
RetABitmap1();
}
方法一的问题是,内存不断的增加,而且即使调用GC.Collect()也无法回收内存,除非关闭窗口。
private void button2_Click(object sender, System.EventArgs e)
{
for(int i = 0; i < 10; i++)
RetABitmap2();
}
方法二的问题是,因为Bitmap的使用并不在Fixed方法的范围内,所以可能出现返回的Bitmap在还没有使用的时候,它的数据就已经被垃圾回收器回收了。解决了立即给分,来者有分。