Is there a memory leak in the System.Drawing.Bitmap or am i just not deallocating the bitmap correct

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hello,
I was doing some drawing with bitmaps and found I was running out of memory quickly. I made a simple program to test this, and it Im guessing the GC isnt collecting the bitmaps after they go out of scope. The following program gives me an Out of Memory
Exception.

<div style="color:Black;background-color:White; <pre>
<span style="color:Blue; public <span style="color:Blue; partial <span style="color:Blue; class MainWindow : Window
{

Random random = <span style="color:Blue; new Random();

<span style="color:Blue; public MainWindow()
{
<span style="color:Blue; for (<span style="color:Blue; int i = 0; i < 1000; i++)
{
Thread.Sleep(33);
<span style="color:Green; //noLeak();
bitmapLeak();
}
InitializeComponent();
}

<span style="color:Blue; void bitmapLeak()
{
System.Drawing.Bitmap bitmap = <span style="color:Blue; new System.Drawing.Bitmap(1000, 1000);
}

<span style="color:Blue; void noLeak()
{
<span style="color:Blue; int count = 100000000;
<span style="color:Blue; byte[] a = <span style="color:Blue; new <span style="color:Blue; byte[count];
random.NextBytes(a);
Console.WriteLine(a[random.Next(100000000)]);
}
}
[/code]

The noLeak() function is garbage collected quickly as expected. The bitmapLeak() function is not garbage collected and the memory usage increases in size until I get an error.
Though I can think of ways around this, i was hoping to find a way to free up this bitmap memory.
Thanks,
Greg

View the full article
 
Back
Top