Hamza_L
Hamza_L

Reputation: 654

How to destroy a usercontrol to free memory?

I'm working on a WPF application, I have a method let's call it GetUIElement(), my method returns a CustomUserControl, and I have a for loop in which I call GetUIElement, the problem is when I have 1000 iterations in the for loop my application consumes too much memory.

PS :

Upvotes: 0

Views: 1010

Answers (3)

paparazzo
paparazzo

Reputation: 45096

Why do you contend your application consumes too much memory?

The GC will collect memory when it needs to.

If GC is waiting until the end of the loop to collect that is because the GC has determined it did not need memory while in the loop.

If the memory comes back down at the end of the loop then there is not a memory leak.

How much memory does Task Manager report?

So your app consumes 1.5 GB of memory.
GC is probably still doing its job.
It is collecting memory then it needs to.

Your app is is consuming so many resources that you cannot run other applications. That does not mean the GC is not doing its job.

What is the purpose of 1000 user controls that you discard?

You could do this but it is not going to fix your program

foreach (var item in Data)
{
   using (var element = GetUIElement(item))
   {
       //...
   }
   System.GC.Collect();
}

Upvotes: 0

T McKeown
T McKeown

Reputation: 12847

from what you've shown there is nothing wrong here, GC doesn't kick in automatically just because an object is de-referenced. If there is a problem, the code you are showing isn't part of it.

If you have a real leak it would possibly due to that created control being stored/ref'd someplace else.

Upvotes: 1

Gaston Siffert
Gaston Siffert

Reputation: 372

You can call the garbage:

System.GC.Collect();

But, I just want to say that your code seem to be strange if you really need it... Do you know that you can create a ListBox with a custom item template ?

Upvotes: 0

Related Questions