# Friday, May 22, 2009
« IKVM 0.40 Release Candidate 1 | Main | Development Snapshot »
.NET 4.0 -- AssemblyBuilderAccess.RunAndCollect

This week .NET 4.0 beta 1 was released. I've been playing around with it a little bit and was very excited to find a new Reflection.Emit feature. If you're a reflection nut like me, the title of this blog entry probably already gave it away. Dynamic assemblies can now be garbage collected!

A Little Demo

Running this simple example will show that a System.Type instance is created and then garbage collected.

using System;
using System.Reflection;
using System.Reflection.Emit;

class RunAndCollectDemo
{
  static void Main()
  {
    Type type = CreateType();
    object obj = Activator.CreateInstance(type);
    Console.WriteLine(obj);
    WeakReference weak = new WeakReference(type);
    type = null;
    obj = null;
    Console.WriteLine("type = " + weak.Target);
    GC.Collect();
    Console.WriteLine("type = " + weak.Target);
  }

  static Type CreateType()
  {
    AssemblyBuilder ab =
      AppDomain.CurrentDomain.DefineDynamicAssembly(
        new AssemblyName("foo"),
        AssemblyBuilderAccess.RunAndCollect);
    ModuleBuilder modb = ab.DefineDynamicModule("foo.dll");
    TypeBuilder tb = modb.DefineType("Foo");
    return tb.CreateType();
  }
}

As you can imagine, this required some pretty deep runtime changes. One of them is that RuntimeMethodHandle is no longer a handle. Previously it contained an unmanaged pointer to the native CLR datastructure corresponding to the method, but now it contains a managed interface reference, because the corresponding method can be garbage collected (I haven't looked into it, but I assume that the interface reference points either to a RuntimeMethodInfo or in the case of a method in a RunAndCollect assembly a proxy that contains a weak reference to the RuntimeMethodInfo. UPDATE: A RuntimeMethodHandle represents a strong reference.)

Somewhat ironically, this change breaks the compilation of ikvm's JniInterface.cs, because it stuffs a RuntimeMethodHandle in unmanaged memory. The fix is fairly straightforward (using a GCHandle to point to the MethodBase instead), but it does reveal an interesting property of C#, if you use unsafe code the (normally hidden) implementation details of managed value types can cause your code to break (and not because you explicitly depend on any internals).

What Does This Mean for IKVM.NET?

It would be really awesome if this feature could be used to finally make ClassLoaders garbage collectable, but unfortunately for that to happen this ancient bug first has to be fixed.

Friday, May 22, 2009 7:26:20 AM (W. Europe Daylight Time, UTC+02:00)  #    Comments [3]