title: working with unmanaged resources
body: <p>I use a 3rd party library which is a wrapper around a native dll. the library contains a type <code>XImage</code>, <code>XImage</code> has some properties and a <code>IntPtr Data()</code> method. <code>XImage</code> also Implements <code>IDisposable</code> but I don't know if it is implemented correctly.</p>
  
  <p>I get many <code>XImage</code>s from TCP connection and show them as a movie in a <code>PictureBox</code>.</p>
  
  <p>I used to convert 'XImage' to <code>System.Drawing.Image</code> and view them in a <code>PictureBox</code> but I got <code>AccessViolationException</code>.</p>
  
  <p>So I made a wrapper around <code>XImage</code> called <code>Frame</code>.</p>
  
  <pre><code>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);
    }
  }
  </code></pre>
  
  <p>and by handling references to <code>Frame</code> I solved the <code>AccessViolationException</code>.
  now I have another Issue, when I run the program from visual studio (F5 - Start Debugging) everything is okay, but when I run it from the <code>.exe</code> file or (ctrl + F5 - Start without debugging) the memory usage is growing larger and larger until I get <code>OutOfMemoryException</code>.(Biuld Configuration: Release - X86). what should I do ?</p>
  
  <p><strong>---- EDIT ----</strong></p>
  
  <p>I found that <code>GC.AddMemoryPressure</code> or <code>GC.RemoveMemoryPressure</code> just makes the garbage collection to run more often and, my problem is now that I have small objects that have a handle to large unmanaged memory, and GC is not collecting these small objects.</p>
  
  <p><strong>---- EDIT ----</strong><br>
  calling <code>GC.Collect</code> will solve the problem during run-time, I set up a timer and call <code>GC.Collect</code> periodically, but it makes the application freeze for a short period, so I don't want to use this approach. </p>