Bitmap.Save, Huge Memory Leak

前端 未结 5 1075
情歌与酒
情歌与酒 2021-01-16 05:02

I have an application where I am taking a bitmap and compressing it using a GZipStream and sending it over a socket, all in memory. I have tracked down the dirty scumbag mem

相关标签:
5条回答
  • 2021-01-16 05:33

    I don't know much about sockets. However, I know one way to stop a memory leak with the Image class is to freeze the bitmap. Hopefully, this post might provide you with some more information. Could the MemoryStream.Dispose be failing? Thereby, creating a memory leak.

    0 讨论(0)
  • 2021-01-16 05:36

    Are you calling the .Dispose() method of your Graphics object? That will cause a memory leak. EDIT: Once you have written the byte[], you are now clear to .Dispose() of the Bitmap object.

    0 讨论(0)
  • 2021-01-16 05:38

    I suggest running your code under CLR Profiler to locate the source of the leak. If it's a managed object of any type (even an unmanaged resource), as long as the bug isn't due to a managed type leaking an unmanaged handle, you'll be able to see where the leak is. If it's in framework code, you can probably work around it using reflection and P/Invoke.

    For example, the Icon type leaks Win32 HICONs in some circumstances. The workaround for this is to manually dispose the HICON by PInvoking the DeleteObject function, using the handle exposed by the Icon.

    0 讨论(0)
  • 2021-01-16 05:39

    You should set the bitmap to null when done working with it, after disposal.

    Also, you may want to invoke the Garbage Collector after disposal of the Bitmap (even though it is an expensive operation): GC.Collect();

    Bitmap holds unmanaged resources - the GC is not always "on the ball" with these. Here is an interesting link regarding the Bitmap class (from the perspective of the compact framework): http://blog.opennetcf.com/ctacke/PermaLink,guid,987041fc-2e13-4bab-930a-f79021225b74.aspx

    0 讨论(0)
  • 2021-01-16 05:43

    Okay, after trying everyones ideas and thoughts and numerous other methods. I finally tried the simple:

    using (frame) {
        frame.Save(outStream, jpegCodec, parameters);
    }
    

    And well, this worked and the memory leak is fixed.. I tried forcefully invoking the garbage collector, disposing the bitmap manually, using P/Invoke DeleteObject, nothing worked, but using a using statement did. So this makes me wonder what happens underthehood on a using statement that I'm missing out on....

    0 讨论(0)
提交回复
热议问题