title: How do I prevent a bitmap variable taking up too much memory when initializing it in a loop?
body: <p>I'm making a screen recording program so how it works is that it take a lot of pictures then stores them to make it into a video, but i ran into a problem when making the program run longer than 8 seconds. It uses way more memory than it should.</p>
  
  <pre><code>            while (DateTime.Now.Minute * 60000 + DateTime.Now.Second * 1000 + DateTime.Now.Millisecond &lt; startTime+20000) {
              memoryImage = new Bitmap(ScreenBounds.Width, ScreenBounds.Height);
              // Create graphics 
              Console.WriteLine("Creating Graphics...");
              Console.WriteLine();
              Graphics memoryGraphics = Graphics.FromImage(memoryImage);
  
              // Copy data from screen 
              Console.WriteLine("Copying data from screen...");
              Console.WriteLine();
              try
              {
                      memoryGraphics.CopyFromScreen(0, 0, 0, 0, ScreenBounds);
              }
              catch (Exception er)
              {
                      Console.WriteLine("Error when copying data from screen error: " + er.Message + " : breaking script");
                      break;
              }
  
              // Save it! 
              Console.WriteLine("Saving the image...");
              images.Add(memoryImage);
              GC.Collect();
              GC.WaitForFullGCComplete();
  </code></pre>
  
  <p>As you can see I tried forcing garbage collection; the problem variable is memoryImage or at least that's what it seems to be I'm not completely sure. How can I get this program to use less memory, so it doesn't crash?</p>
  
  <p>UPDATE:
  I added memoryImage.Dispose(); to the end of the first part which fixed the memory issue but now I get the error:</p>
  
  <p>An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll</p>
  
  <p>Additional information: Parameter is not valid.</p>
  
  <p>in this block of code:</p>
  
  <pre><code>            VideoWriter video = new VideoWriter(@"outputVideo.avi", (int)AvgFPSList.Average(), Screen.PrimaryScreen.Bounds.Size, true);
          for (int x = 0; x &lt; images.Count; x++)
          {
              Image&lt;Emgu.CV.Structure.Bgr, Byte&gt; img = new Image&lt;Emgu.CV.Structure.Bgr, Byte&gt;(images[x]); &lt;&lt; error here
              video.Write(img.Mat);
          }
  </code></pre>