It looks like you are using
System.Drawing
and
System.Windows.Forms
. You should always tag the libraries you use for UI and graphics.
Look at the
Bitmap
class. It implements
System.IDisposable
. It means that, whatever you do, you should eventually call
System.IDisposable.Dispose
for each
Bitmap
object when you no longer use it.
Some background:
You never need to free managed memory. It is reclaimed by a Garbage Collector. It does not mean that managed memory leak is impossible. It is possible, but it can be a result of some design bugs. Please see my past answers:
Garbage collectotion takes care of all the memory management[
^],
deferring varirable inside the loop can cuase memory leak?[
^],
Best way to get rid of a public static List Causing an Out of Memory[
^],
Memory management in MDI forms[
^].
In contrast, the unrelated
System.IDisposable
mechanism is designed to help the developers to guarantee that some clean up action is always called, on a universal basis. The clean up action itself can be absolutely anything. One application of it is reclaiming of unmanaged resources, which is needed for
Image
and many other objects, in particular, GDI, and a lot more.
Finally, your other problem is using the class
PictureBox
. It is poorly redundant and should be used only to simplify the simplest cases, such as showing some static image. In most more complex cases, it only presents hassles and use resources giving nothing in return. You should use your own rendering of graphics, which is really simple. Please see my past answers:
How do I clear a panel from old drawing[
^],
draw a rectangle in C#[
^],
Append a picture within picturebox[
^].
[EDIT]
After OP's clarification:
The last paragraph above is about
System.Windows.Forms.PictureBox
: don't use it for anything dynamic/interactive/animated.
I did not mean
AForge.Controls.PictureBox
(which I did not use so far).
Again, please always provide fully-qualified type names when asking questions.
—SA