I have a dynamic module which gets types added to it as my application runs. The module is created via the following code:
var assemblyName = new AssemblyName("MyAssembly");
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
MyClass.RuntimeBoundDerivedTypesModule = assemblyBuilder.DefineDynamicModule("MainModule");
Other parts of the application also sometimes call GetTypes() on the module's assembly. Occasionally, when this happens I get TypeLoadException for one of the types in the dynamic module. The stack trace is:
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.Reflection.Assembly.GetTypes()
My question is: what could cause this exception? Are runtime modules truly thread-safe or can there be race conditions where GetTypes() gets called while a type is partway through being created?
EDIT: here's a small snippet of code that reproduces the bug reliably for me. It now seems that the exception occurs if GetTypes() is called between DefineType() and CreateType():
var assemblyName = new AssemblyName("MyAssembly");
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder m = assemblyBuilder.DefineDynamicModule("foo");
Action doStuff = () => {
try {
if (!m.GetTypes().Any() || Guid.NewGuid().GetHashCode() % 2 == 0) {
var t = m.DefineType(
"MyType" + Guid.NewGuid().ToString().Replace("-", ""),
TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout,
typeof(object)
);
Thread.Sleep(1);
t.CreateType();
}
else {
//m.GetTypes(); // interestingly, this always works
assemblyBuilder.GetTypes();
"it worked!".Dump();
}
} catch (Exception ex) {
Console.WriteLine(ex);
}
};
// in synchronous mode, I only see failures if I leave out the call to CreateType(). In that
// case, it never works
//Enumerable.Range(1, 1000)
// .ToList()
// .ForEach(_ => doStuff());
// in the async mode, I always see failures with Thread.Sleep() and sometimes
// see them if I take the sleep out. I often see a mix of failures and "It worked!"
var threads = Enumerable.Range(1, 100).Select(t => new Thread(() => doStuff()))
.ToList();
threads.ForEach(t => t.Start());
threads.ForEach(t => t.Join());