Question

From MSDN:

You can use the DynamicMethod class to generate and execute a method at run time, without having to generate a dynamic assembly and a dynamic type to contain the method. The executable code created by the just-in-time (JIT) compiler is reclaimed when the DynamicMethod object is reclaimed. Dynamic methods are the most efficient way to generate and execute small amounts of code.

I have the following code:

Type returnType = typeof(string);
Type[] argTypes = { typeof(string), typeof(IEnumerable<string>) };

var dynamicMethod = new DynamicMethod("DynamicMethod1", returnType, argTypes);
ILGenerator ilGen = dynamicMethod.GetILGenerator();
const string Returned = "returned";
ilGen.Emit(OpCodes.Ldstr, Returned);
ilGen.Emit(OpCodes.Ret);

var handler =
    (Func<string, IEnumerable<string>, string>)
    dynamicMethod.CreateDelegate(typeof(Func<string, IEnumerable<string>, string>));

i.e., i create dynamic method with some simple body, then i want to save delegate to static property. After several calls of this delegate i want to reclaim/collect method and recreate it with another body (i wrote interpreted language, that interprets my custom syntax to MSIL bytecode - something like compiler) and save new delegate to static property.

How i can explicitly collect/reclaim dynamic method?

Was it helpful?

Solution

You can't dispose of a DynamicMethod explicitly because it doesn't implement the IDisposable interface. You can however tell the GarbageCollector when you want it to collect: System.GC.Collect();

This "Forces an immediate garbage collection of all generations" according to MSDN

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top