Reputation: 10509
I noticed in testing, that multiple calls to the following code creates a memory leak :
object obj = Activator.CreateInstance(Type.GetType(arg2.DeclaringType.FullName));
arg2.Invoke(obj, new object[] { arg3 });
For the above code, arg2
is MethodInfo
type ; arg3
is string[]
Even if I add obj = null;
after the Invoke, it seems that GAC doesn't collect this object for cleanup. (yes, I know setting an object to null is a poor excuse for dispose(), however as this is a generic method, there may or may not be a dispose() available in the class, and tested with assemblies that do have dispose, they are not unloaded after use)
I have consider using a cache mechanism where the loaded assembly is stored in a dictionary for subsequent lookups, however there is no guarantee that GAC won't come and clean it up later making that object in dictionary unusable (among other disasters).
How can I force an unload of the class (similar to the way I can force it to load by calling Activate
) once I am finished with it ?
Upvotes: 1
Views: 2379
Reputation: 4806
Let's get this straight, you can not unload an assembly when it has been loaded unless you unload the entire Application Domain.
(and if you want to know why : check this blog)
However, with a class it is different, you are talking about releasing it from memory. First of all, are you sure that no other object have an access to it ?
When you are sure of that, know that the Garbage Collector will release the memory of the unreferenced objects whenever it wants to, so talking about memory leak might be a bit prematured...
You can however force the Garbage Collector to clean up the memory by calling GC.Collect()
Upvotes: 1