Reputation: 654
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 :
In the constructor and the destructor of CustomUserControl I put some debug code to get an idea about the life cycle of my objects, and I saw that they are all destroyed at the same time after the loop, wich explain why my application consumes too much memory, they are all kept in memory until the end of the loop. I hope I was clear, dont hesitate to tell me if you want more explanation. and here is some portions of the code :
foreach (var item in Data)
{
var element = GetUIElement(item);
//...
}
public FrameworkElement GetUIElement()
{
CustomUserControl control = new CustomUserControl();
control.StartButton.Style = Application.Current.Resources["StandardButton"] as Style;
return control;
}
Upvotes: 0
Views: 1010
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
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
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