Reputation: 83254
I have a function that takes in a list of functors:
public void RunFunc(List<Func<double, double>> functorList)
The thing is that the Func<double, double>
are assigned with methods from different objects. My concern now is that the garbage collector would always hold pointers to these methods, and always hold the memory for those objects because the GC doesn't know how to dispose them.
Am I right? Will RunFunc
cause memory leak? If yes, what I should do to free the memory that are held by List<Func<double, double>> functorList
?
Upvotes: 2
Views: 2368
Reputation: 45252
You are creating a list of delegates, and while this list exists it will hold a reference to every object that each delegate references.
If the RunFunc
method stores this list as a member, than the objects will not be garbage collected as long as the list is stored. This is a good thing - otherwise it might later try calling a function on an object that has been destroyed.
As soon as the list stops being referenced it will no longer be preventing the objects from being garbage collected.
So, in answer to your question, RunFunc
really isn't any different from any other CLR method, and the same garbage collection rules will apply as always.
Here's a simpler example:
Action myAction = null;
{
var widget = new Widget();
myAction = () => { widget.ScooblyWob() };
}
// the widget object has gone out of scope, but will stay in memory
// It is not a candidate for garbage collection, because
// it is being referenced by the myAction function.
myAction();
// Even though I have no explicit references to the widget,
// I just called a function on it!
myAction = null;
// Now the action has been dereferenced,
// so the widget is a garbage collection candidate
Upvotes: 3
Reputation: 273264
No, this will not cause a memory leak.
As soon as the List<>
becomes unreachable it will be collected. The Func<>
items are outgoinf references. Only incoming references can keep something alive.
Upvotes: 4