2009-10-14 22 views
0

我一直trying to swap images in a PictureBox in a C++/CLI application但我的解决方案似乎有内存泄漏:为什么我的PictureBox加载例程泄漏内存?

System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) 
{ 
    // Pick a new bitmap 
    static int resource = IDB_BITMAP1; 
    if(resource == IDB_BITMAP2) 
    { 
     resource = IDB_BITMAP1; 
    } 
    else 
    { 
     resource = IDB_BITMAP2; 
    } 

    // Get the primary module 
    Module^ mod = Assembly::GetExecutingAssembly()->GetModules()[0]; 

    // Get the instance handle 
    IntPtr hinst = Marshal::GetHINSTANCE(mod); 

    // Get the bitmap as unmanaged 
    HANDLE hbi = LoadImage((HINSTANCE) hinst.ToPointer(),MAKEINTRESOURCE(resource),IMAGE_BITMAP,0,0,LR_DEFAULTCOLOR); 

    // Import the unmanaged bitmap into the managed side 
    Bitmap^ bi = Bitmap::FromHbitmap(IntPtr(hbi)); 

    // Remove any previously stored images 
    if(m_pictureBox1->Image != nullptr) 
    { 
     delete m_pictureBox1->Image; 
     m_pictureBox1->Image = nullptr; 
    } 

    // Insert the bitmap into the picture box 
    m_pictureBox1->Image = bi; 

    // Free up the unmanaged bitmap 
    DeleteObject(hbi); 
} 

据我所看到的,我明确地释放内存那么,为什么任务管理器报告的〜24K的内存增加每次点击按钮?

回答

1

两个词:垃圾收集

+0

这是我最初的反应,但明确删除的对象应该绕过这些效果不应该? –

+0

我认为清理只会清理未管理的一面。其余的将在稍后的时间点由GC进行清理... – KristoferA

+0

这将有道理.. –

0

奇怪的是,这实际上看起来当你将鼠标悬停在按钮所致。每次你这样做的时候,内存跳转,但在足够的鼠标悬停后,内存使用量稳定下来。实际点击按钮(即调用我的例程)不会导致任何泄漏。