For performance optimization, I dynamically create new types per user request using the following code:
var dynamicAssemblyName = new AssemblyName(assemblyName);
AssemblyBuilder dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(dynamicAssemblyName, AssemblyBuilderAccess.RunAndCollect);
ModuleBuilder moduleBuilder = dynamicAssembly.DefineDynamicModule(assemblyName);
Then I use that moduleBuilder
to emit the type.
This creates a new dynamic assembly per request. So I could end up with many of those during the lifetime of the app. So, I'm worried that the resources will be freed. Therefore, I'm using AssemblyBuilderAccess.RunAndCollect to make this possible. The msdn says:
The dynamic assembly can be unloaded and its memory reclaimed, subject to the restrictions described in Collectible Assemblies for Dynamic Type Generation.
I just didn't find how to unload the dynamic assembly and unfortunately the link to the Collectible Assemblies for Dynamic Type Generation topic is broken.
A no-longer-maintained version of that page seems to indicated that the unloading happens automatically once the emitted type gets out of scope. Can I trust this?
A no-longer-maintained version of that page seems to indicated that the unloading happens automatically once the emitted type gets out of scope. Can I trust this?
Yes. The option is called RunAndCollect
, because such assemblies are automatically unloaded when the garbage collector decides they are no longer needed. There is no API to force unloading of collectible assemblies (apart from triggering GC).
You can verify this by inspecting currently loaded assemblies using AppDomain.CurrentDomain.GetAssemblies()
, then calling GC.Collect()
to trigger garbage collection and then inspecting loaded assemblies again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With