为什么我的PictureBox加载例程会泄漏内存?

时间:2009-10-14 12:53:25

标签: wpf memory-leaks c++-cli picturebox

我一直trying to swap images in a PictureBox in a C++/CLI application但我的解决方案似乎有内存泄漏:

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?

2 个答案:

答案 0 :(得分:1)

两个字:垃圾收集

答案 1 :(得分:0)

奇怪的是,当您将鼠标悬停在按钮上时,实际上会出现这种情况。每次执行此操作时,内存会跳转,但经过足够的鼠标操作后,内存使用量会稳定下来。按钮上的实际点击(即调用我的例程)不会导致任何泄漏。