我有一个动态模块,可以在我的应用程序运行时添加类型。该模块通过以下代码创建:
var assemblyName = new AssemblyName("MyAssembly");
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
MyClass.RuntimeBoundDerivedTypesModule = assemblyBuilder.DefineDynamicModule("MainModule");
应用程序的其他部分有时也会在模块的程序集上调用GetTypes()。偶尔,当发生这种情况时,我会为动态模块中的一个类型获取TypeLoadException。堆栈跟踪是:
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.Reflection.Assembly.GetTypes()
我的问题是:什么可能导致此异常?运行时模块是否真的是线程安全的,或者是否存在竞争条件,其中GetTypes()被调用而类型在创建过程中途?
编辑:这是一小段代码,可以为我可靠地再现错误。现在看来,如果在DefineType()和CreateType()之间调用GetTypes(),则会发生异常:
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());
答案 0 :(得分:0)
ModuleBuilder实际上大多数实例方法在.Net中都不是线程安全的。请参见底部:http://msdn.microsoft.com/en-us/library/system.reflection.emit.modulebuilder.aspx