Pregunta

I'm stuck with how to free resources, used by System::Image and System::Drawing::Graphic

Any help would be appreciated.

[System::Runtime::InteropServices::DllImport("gdi32.dll")];

static bool DeleteObject(IntPtr hObject);

private: System::Void button6_Click(System::Object^  sender, System::EventArgs^  e) {
    //some code here
    System::Drawing::Bitmap ^ bitmap = gcnew Bitmap(5000, 3000); //+65 MB RAM
    IntPtr hbitmap = bitmap -> GetHbitmap(); //+75 MB
    Image ^ imgType1 = Image::FromHbitmap(hbitmap); //+60 MB
    System::Drawing::Graphics ^ grrType1 = System::Drawing::Graphics::FromImage(imgType1); //+0 MB
    //some code here
    DeleteObject(hbitmap); //-60 MB
    delete grrType1; //-0 MB;
}
¿Fue útil?

Solución

You are forgetting to call delete imgType1; and delete bitmap;. Which prevents their unmanaged memory allocations from getting released until the garbage collector runs. That can take a while.

This code looks like it was paralyzed by not knowing that the Bitmap class derives from Image, thus thinking that it was necessary to convert Bitmap to Image explicitly. Not necessary, you can create the Graphics object from Bitmap as well. And overlooking stack semantics to get objects automatically disposed. Which works on Bitmap but not on Graphics since it doesn't have a public constructor. Make it look like this instead

Bitmap bitmap(5000, 3000);     // Note the missing ^ hat
Graphics^ graphics = Graphics::FromImage(%bitmap);
try {
    // some code here
    //...
}
finally {
    delete graphics;
}

Using try/finally to ensure that the Graphics object is disposed is pretty serious overkill in a button's Click event handler, but it I suspect that it might not remain there. Do keep in mind that Task Manager is not a memory profiler.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top