I know how to use IDisposable
interface in my class. But, I don't know how to free memory which is allocated by my class variables? for example in my class i have created a List<Bitmap>
with the 500 bitmap images in the list and I am clearing this list in the dispose method. But, it shows same result when i fetch the total memory using GC.GetTotalMemory()
.
Here, I have created a sample class implemented by IDisposable
interface.
public class disposable : IDisposable
{
List<Bitmap> list = new List<Bitmap>();
public disposable()
{
for (int i=0; i< 500; i++)
{
Bitmap bmp = new Bitmap(1024,768);
using (Graphics g = Graphics.FromImage(bmp))
{
g.FillRectangle(Brushes.Red, new Rectangle(0,0,1024,768));
}
list.Add(bmp);
}
}
public void Dispose()
{
list.Clear();
list = null;
}
}
Then I have executed following code
static void Main(string[] args)
{
long l1 = GC.GetTotalMemory(true);
using (disposable d = new disposable())
{
//nothing to do
}
long l2 = GC.GetTotalMemory(false);
Console.WriteLine(l1.ToString());
Console.WriteLine(l2.ToString());
Console.ReadKey();
}
The output says.
181764 //bytes before creating object of disposable class
222724 //bytes after creating object of disposable class
Then I have tried without using
keyword with simple declaration.
Dim d As New disposable();
But, it is giving me same result.
So, my question is why memory don't get free which is allocated by those bitmap images even I dispose the object. It doesn't make any difference. I am clearing all items from the list and also assigning null value to list
object.
I have also tried same thing with declaring byte array instead of list<Bitmap>
and SqlConnection
object.
But, it was not showing any difference in total memory allocated between both methods(simple declaration and using
statement).
long l1 = GC.GetTotalMemory(true);
//SqlConnection cnn = new SqlConnection(""); //1st Method
using (SqlConnection cnn = new SqlConnection("")) //2nd Method
{
//nothing to do
}
long l2 = GC.GetTotalMemory(false);
Console.WriteLine(l1.ToString());
Console.WriteLine(l2.ToString());
I can't understand why it does not clear the memory which is allocated by both managed and un-managed objects?