title: C# Bitmap dispose memory usage
body: <p>I'm currently implementing webcam functionality into an app I'm creating however I've had some issues with memory usage.</p>
  
  <p>My function is as shown below</p>
  
  <p>This is the first implementation</p>
  
  <pre><code>private void webcam_newFrame(object sender, NewFrameEventArgs eventArgs) {
      if (!_pause) {
          var img = (Bitmap) eventArgs.Frame.Clone();
          pbPicture.BackgroundImage = img;            
      }
  }
  </code></pre>
  
  <p>However this code caused huge memory leaks, running up 2gb (of ram I assume). Before crashing due to out of memory.
  I then changed the code to dispose of the Bitmap, like so</p>
  
  <pre><code>private void webcam_newFrame(object sender, NewFrameEventArgs eventArgs) {
      if (!_pause) {
          var img = (Bitmap) eventArgs.Frame.Clone();
          pbPicture.BackgroundImage = img;
          img.Dispose(); // This causes exception
      }
  }
  </code></pre>
  
  <p>This causes Exception thrown: 'System.ArgumentException' in System.Drawing.dll. </p>
  
  <p>Additional information: Parameter is not valid.</p>
  
  <p>On the following code which calls this form to be shown:</p>
  
  <pre><code>WebcamForm wForm = new WebcamForm();
  wForm.ShowDialog();
  </code></pre>
  
  <p>So I then changed the function to this:</p>
  
  <pre><code>private void webcam_newFrame(object sender, NewFrameEventArgs eventArgs) {
      if (!_pause) {
          pbPicture.BackgroundImage = (Bitmap)eventArgs.Frame.Clone();
          GC.Collect();
      }
  }
  </code></pre>
  
  <p>This code works correctly, memory usage stays around 360mb which is consistent and a reasonable figure considering the application. </p>
  
  <p>My question is, is forcing a garbage collection on every frame a good solution to this? Are there any potential issues? </p>
  
  <p>I'm sure I've seen answers in the past that forcing garbage collection is a bad thing to do, however I can't think of any alternative ways around this problem.</p>
  
  <p>Cheers</p>