veadrait
veadrait

Reputation: 21

How to totaly clear memory after remove object in C#

How to clear memory after using object?

A read a lot of question on this forum and every body say: Use myObject=null for delete your object. Like this:

Car myCar = new Car();

//do stuff
myCar.horn();

myCar = null; // <-- DELETE

In my program, I am creating a lot of Form (public partial class Myform: Form).

Like this:

ArrayList listOfMyForms = new ArrayList();

for(int i = 0; i < 100; i++)
{
   listOfMyForms.Add(new Myform());
}

So.. I make 100 times object...

BUT if I delete all using remove method (call in for loop):

public void remove(Myform someForm)
{
    listOfMyForms.Remove(someForm);
    someForm = null;
    GC.Collect();
}

I CAN SEE FULL MEMORY (20mb) in Visual Studio section: Diagnostic tools (Process monitor


Before creating 100 forms is memory on 16mb.

After creating 100 forms is memory on 20mb.

After clean all forms is memory on 20mb.


So.. How can i free my memory?

I hope, you understand my problem. Sorry for my bad english :-)

Upvotes: 2

Views: 5880

Answers (2)

bot_insane
bot_insane

Reputation: 2604

I think this things will help you understand:

  1. When objects are collected by GC the associated memory may or may not be freed to OS. CLR manages this process automatically.
  2. When calling GC.Collect() it starts collecting and return immediately. It doesn't wait for finishing clean-up. To force your program to wait you need to call GC.WaitForPendingFinalizers() after GC.Collect().
  3. Form class is implementing IDisposable and is using unmanaged resources. For cleaning it you need to call Dispose(true)

FYI: In most cases you really didn't need to care about deleting objects manually, hope you know what are you doing.

Upvotes: 3

Bewar Salah
Bewar Salah

Reputation: 567

use the bellow code.

public void remove(Myform someForm)
{
    someForm.Dispose(true)
}

Because forms use managed code. When using managed code you need to Implement IDisposable, and call Dispose method whenever you are no longer in need of the object.

Upvotes: 0

Related Questions