Hello,
I encountered an issue related to multiple calls to the DefineDynamicAssemblymethod from parallel threads. It cannot be reproduced reliably and occurs rarely. No exception is thrown. Application execution locks when multiple threads call this method at the same time.
Here is a console app code that can reproduce it sometimes. Eventually, it will crash with OutOfMemory.
public partial class App : Application { int i = 0; protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); Test(); } void Test() { while (true) { var t1 = new Thread(TryGetBuilder); var t2 = new Thread(TryGetBuilder); var t3 = new Thread(TryGetBuilder); t1.Start(); t2.Start(); t3.Start(); } } void TryGetBuilder() { var builder = ModuleBuilderSource.GetModuleBuilder(); Console.WriteLine($"Success {i} - {builder.FullName}"); i++; } } public class ModuleBuilderSource { public static AssemblyBuilder GetModuleBuilder() { return AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run); } }
Do you have any advice for this scenario?