问题
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?
回答1:
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).
回答2:
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.
来源:https://stackoverflow.com/questions/3065386/can-the-net-methodinfo-cache-be-cleared-or-disabled