I use a third-party library, which is a wrapper around the native DLL. the library contains the XImage
type, XImage
has some properties and the IntPtr Data()
method. XImage
also implements IDisposable
, but I do not know if it is implemented correctly.
I get a lot of XImage
from a TCP connection and show them as a movie in a PictureBox
.
I used to convert 'XImage' to System.Drawing.Image
and looked at them in a PictureBox
, but got an AccessViolationException
.
So, I did a wrapper around XImage
called Frame
.
public class Frame : IDisposable { public uint size { get; private set; } private Image image; public XImage XImage { get; set; } public Image Image { get { return image ?? (image = GetBitmap(this.XImage)); } } public DateTime Time { get; set; } public Frame(XImage xImage) { this.XImage = xImage; this.size = XImage.ImageBufferSize(); GC.AddMemoryPressure(size); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~Frame() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (disposing) { try { image.Dispose(); } catch { } finally { image = null; } try { MImage.Dispose(); } catch { } finally { XImage = null; } } GC.RemoveMemoryPressure(size); } }
and handling Frame
references, I resolved an AccessViolationException
. now I have one more problem when I run the program from visual studio (F5 - Start Debugging), everything is fine, but when I run it from the .exe
or (ctrl + F5 - Start without debugging), the memory usage grows all more and more until I get an OutOfMemoryException
. (Biuld Configuration: Release - X86). what should I do?
---- EDIT ----
I found that GC.AddMemoryPressure
or GC.RemoveMemoryPressure
just makes garbage collection work more often, and now my problem is that I have small objects that have a large unmanaged memory descriptor, and GC does not collect these small objects.
---- EDIT ----
calling GC.Collect
will solve the problem at runtime, I periodically set the timer and call GC.Collect
, but this makes the application freeze for a short period, so I do not want to use this approach.
source share