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?
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
RunFuncmethod 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,
RunFuncreally isn’t any different from any other CLR method, and the same garbage collection rules will apply as always.Here’s a simpler example: