Search code examples
c#reflection.emit

Build a disposable method at runtime


My program creates in anytime new methods (Using MethodBuilder with array of byte\IL) that it executes them once and discard the reference to them. I found that they don't actually affected by the GC. Is there a way to let the GC collect them or dispose them?

I found that the problem is that to create new method, need to load it's assembly that can't be unloaded after. I need to run those methods on the main appdomain. (It creates objects or modifying some) Is there an alternative to MethodBuilder and just execute those byte\IL anyway?


Solution

  • Use DynamicMethod if you only need to emit a method that can be garbage collected later. From the docs:

    Defines and represents a dynamic method that can be compiled, executed, and discarded. Discarded methods are available for garbage collection.

    If you need to build a type dynamically then you need to define a dynamic assembly for it that can be collected. To do that use AssemblyBuilder.DefineDynamicAssembly with the AssemblyBuilderAccess.RunAndCollect option. There are some restrictions on what you can do in a collectible assembly detailed here.