views:

34

answers:

2

Per MSDN, calling Type.GetMethods() stores reflected method information in a MemberInfo cache so the expensive operation doesn't have to be performed again.

I have an application that scans assemblies/types, looking for methods that match a given specification. The problem is that memory consumption increases significantly (especially with large numbers of referenced assemblies) since .NET hangs onto the method metadata.

Is there any way to clear or disable this MemberInfo cache?

+2  A: 

I don't think so. One trick would be to do this work in an AppDomain. You could create a new AppDomain, do all of your work, report your results, then unload the AppDomain. Not a trivial task and fairly slow but it is the only way to effectively unload assemblies or reflection related caches (that I know of).

justin.m.chase
I'm getting a list of assemblies to scan by calling `AppDomain.CurrentDomain.GetAssemblies()`. How do I access the currently loaded assemblies from a different AppDomain?
Anton
Pass the result of AppDomain.CurrentDomain.GetAssemblies().Select(a => a.FullName) to the other AppDomain and then call Assembly.ReflectionOnlyLoad for each.
dkackman
Super slow, but it works. Too slow for my project.
Anton
A: 

You can reduce the memory consumption somewhat if you don't need to execute the methods by using Assembly.ReflectionOnlyLoad(string). Unloading the assemblies will still require unloading the AppDomain, however, so if your problem is a leak (your program stays open, user keeps passing you new assemblies to look at indefinitely), instead of just high memory use, this won't help.

Doug McClean
Unfortunately, I do need to execute the methods that match the signature I'm searching for.
Anton