Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unload a dynamic assembly created with RunAndCollect?

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?

like image 440
Dejan Avatar asked Jun 19 '17 14:06

Dejan


1 Answers

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.

like image 59
svick Avatar answered Nov 18 '22 13:11

svick