何时处理GDI对象,特别是位图?

4

我最近了解到需要处理GDI对象,因为GC不像C#中的其他对象那样对它们进行处理。我有一些位图,希望它们在表单的生命周期内可用,但我对一些事情不确定...

  1. When recreating a bitmap object, do I need to dispose of the original object first? I'm thinking not, but I thought I'd check. For example:

    // Global
    Bitmap bmp;
    
    // In form constructor...
    bmp = new Bitmap(source);
    
    // In a function...
    if(bmp != null) {
      bmp.Dispose
      bmp = null
    }
    bmp = new Bitmap(source2);
    
    // On paint (if bmp not null)...
    DrawImage(bmp, rectangle);
    
  2. Because I want to keep bitmaps for the lifetime of the form, can I simply dispose of them on the form close event?

  3. Is there a better alternative than preserving the bitmaps? Creating each bitmap from a file and disposing on paint performs too slowly. Using Image instead of Bitmap lowers the image quality.

非常感谢您!


请记住,GC从不调用.Dispose()。无论是GDI对象还是任何其他.NET对象,您都必须明确调用.Dispose() - Enigmativity
1个回答

4
  1. 是的,在这种情况下,您绝对必须调用“Dispose”。不这样做会导致旧内存泄漏。
  2. 任何需要具有形式生命周期的位图都可以在“Close”中处理。不过,我不会为每个位图执行此操作,因为在同一时间内将占用大量内存,很快
  3. 这取决于您的使用情况。如果您正在运行某种动画,质量真的需要如此好吗?内存使用量与速度相比,图像质量,只有您知道什么最重要。但是三者你不能兼得。

如果您暂时使用Bitmap,应考虑将其包装在using块中,以便自动处理:

using (Bitmap myBitmap = new Bitmap(src))
{
  //Do stuff with the temp bitmap
}

@Bradley:为什么在Close中处理每个Bitmap会“快速消耗内存”? - Andy
1
@Andy,占用内存的不是释放资源,而是在内存中拥有大量未释放的Bitmap对象。已编辑以澄清此问题。 - BradleyDotNET

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接