title: C# "Out Of Memory Exception" on returning variable accessor
body: <p>I am getting an Out Of Memory Exception when I attempt to new a Bitmap and return it through a "get" accessor.  The Bitmap is of size 640x480 with depth Int32.</p>
  
  <p>My suspicion is that the C# Garbage Collector is unable to delete these old Bitmaps because they are being returned in the accessor to my variable.  I have well over 2GB available so I wouldn't imagine that this "small" image is taking up too much memory.  Unfortunately I HAVE to new the Bitmap due to thread locking issues (<a href="https://stackoverflow.com/questions/14596429/trouble-with-locking-an-image-between-threads">Trouble with locking an image between threads</a>)  The code is as follows:</p>
  
  <pre><code>public Bitmap LiveFrame { get { return GetFrame(500); } }
  </code></pre>
  
  <p>.....</p>
  
  <pre><code>private Bitmap GetFrame(int timeout)
  {
     Bitmap ret = null;
     //CLEyeCameraGetFrame places image data into this._PrivateBitmap
     bool success = CLEyeCameraGetFrame(_Camera, _PtrBmpPixels, timeout);  
  
     if(success) 
       ret = new Bitmap(this._PrivateBitmap);
      return ret;
  }
  </code></pre>
  
  <p>Note on unmanaged code:
  CLEyeCameraGetFrame is in an unmanaged DLL.  I allocate _PtrBmpPixels using Marshal.AllocHGlobal earlier in the code and don't touch it until freeing when closing the app.  _PtrBmpPixels was used in the creation of the Bitmap _PrivateBitmap through its constructor that accepts the IntPtr argument "scan0".  Thus, whenever _PtrBmpPixels is updated via CLEyeCameraGetFrame, _PrivateBitmap is also updated.</p>
  
  <p>I attempted to fix this by Disposing the PcitureBox Bitmap before reusing it, but that broke the PictureBox display.  I have two threads updating two different PictureBox/ImageBoxes:</p>
  
  <pre><code>lock (_CameraLocker)
  {
    if (_VideoPlaying)
    {
      try{
           if (pbLiveFeed.Image != null)
              pbLiveFeed.Image.Dispose();
  
           pbLiveFeed.Image = _Camera.LiveFrame;
           pbLiveFeed.Invalidate();
         }catch (Exception ex) { }
  }
  </code></pre>
  
  <p>....</p>
  
  <pre><code>lock (_CameraLocker)
  {
     try{
          if (ibProcessed.Image != null)
            ibProcessed.Image.Dispose();
          procImage = new Image&lt;Bgra, Int32&gt;(_Camera.LiveFrame);
          procImage.Draw(new Rectangle(10, 20, 20, 15), new Bgra(1.0, 1.0, 1.0, 1.0), 5);
  
          ibProcessed.Image = procImage;
        }catch (Exception ex) { }
  }
  </code></pre>
  
  <p>Could Garbage collection be the cause of this?  Is it not safe to return a newed object from a get accessor?</p>