【问题标题】:When can a dynamic module have a type load exception?动态模块什么时候可以有类型加载异常?
【发布时间】:2013-08-22 17:26:59
【问题描述】:

我有一个动态模块,它会在我的应用程序运行时将类型添加到其中。该模块是通过以下代码创建的:

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());

【问题讨论】:

    标签: c# reflection typeloadexception dynamic-assemblies


    【解决方案1】:

    ModuleBuilder 和事实上大多数实例方法在 .Net 中都不是线程安全的。见底部:http://msdn.microsoft.com/en-us/library/system.reflection.emit.modulebuilder.aspx

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 1970-01-01
      • 2015-06-11
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      • 2018-11-17
      • 2011-11-25
      • 1970-01-01
      相关资源
      最近更新 更多