title: load 1000 images in c# without out-of-memory exception
body: <p>I want to add <strong>1000</strong> images (each size is (40 to 100) KB) in a panel at run time in a desktop application. At first user browses all the images and load them on a panel. When it loads images one after another then memory usage shown in the task manager increases rapidly and after a certain number of images it shows the “Out of Memory Exception”. Where is the fault in my code? </p>
  
  <p>Before loading the 700 images task manager shows <strong>1.05 GB</strong> memory usage.
  After loading task manager shows <strong>2.04 GB</strong> and 2 GB RAM overflows</p>
  
  <pre><code>int picnumber = 0;
          int numberOfImages = 12;
  
          numberOfImages = Convert.ToInt32(textBox1.Text.ToString());
  
          for (int i = 0; i &lt; numberOfImages; i++)
          {
              GroupBox gBox = new GroupBox();
  
              picnumber++;
  
  
              ////////////////////////////////
  
              // calculate the position of the groupbox where it is placed.
              if ((picnumber % 3) == 1)
              {
                  x = initX;
              }
              else
              {
                  if ((picnumber % 3) == 0)
                  {
                      x = initX + 2 * (130 + 20);
                  }
                  else
                  {
                      x = initX + 130 + 20;
                  }
  
              }
              ///////////////////////////////////
  
  
              System.Drawing.Point CurrentPoint;
  
              CurrentPoint = panel1.AutoScrollPosition;
              y = initY + ((picnumber - 1) / 3) * (130 + 20) - (Math.Abs(panel1.AutoScrollPosition.Y));
  
              gBox.Text = picnumber.ToString();
  
              //place the groupbox in the appropriate position.
              gBox.Location = new System.Drawing.Point(x, y);
              gBox.Size = new System.Drawing.Size(130, 130);
  
              Bitmap btmap = new Bitmap(@"E:\43.jpg");
              // attach the image to the groupbox
              gBox.BackgroundImage = btmap;
              **gBox.BackgroundImageLayout = ImageLayout.Stretch;
              // add the groupbox that contains image to the panel.
              panel1.Controls.Add(gBox);**
  </code></pre>
  
  <p><strong>But I have seen some applications that can load huge number of images and takes memory that is negligible, for example, “Batch Image Resizer”( <a href="http://www.jklnsoft.com/" rel="nofollow">http://www.jklnsoft.com/</a>)</strong></p>
  
  <p><strong>How does the application handle memory? What mechanism do they follow?</strong></p>
  
  <p>Before loading the 700 images task manager shows 1.05 GB memory usage.
  After loading task manager shows 1.06 GB</p>
  
  <p>Development environment:
  C#.net framework 4,
  windows xp,
  Visual Studio 2010,
  RAM: 2 GB</p>