Cristiano Coelho
Cristiano Coelho

Reputation: 1735

C# Reflection, assembly.load byte[]

im using Assembly.Load(byte[]) to dynamically load some dlls, which the user adds when wanted. What happens if i call Assembly.Load(byte[]) multiple times, being that byte[] loaded from the same time? Im asking this because in my program, the call to load the dll is done every time its needed, rather than saving a reference to it somewhere. Would it load the same dll multiple times? Would it only load it once and update the already loaded one? Checking visual studio debugger theres only one copy of the dll so it seems fine, but raises another question. I tried to modify the dll, and adding a new one (with a newer version) now having both dll files, the old and the new one, and im calling Assembly.Load(byte[]) to both of them (the old and the new), one by one, like this: load old dll, use it, load new dll, use it. They work fine, both the old and the new, but theres only one of them loaded in, so this makes me think the second load overwrites the old one, how does this work? Is there any risk im having? What happens if multiple users load them? (for example a web app using the method which loads and uses both dlls)

Upvotes: 0

Views: 2134

Answers (1)

Christopher Currens
Christopher Currens

Reputation: 30695

I can't answer all of your questions, because I don't know all of them. But I imagine you could write a test application to figure out some of the other ones.

What happens if i call Assembly.Load(byte[]) multiple times, being that byte[] loaded from the same time?

It will load a new assembly each time you call Assembly.Load(byte[]) regardless if you use the same byte array or read it from a file each time.

You can check it out for yourself:

// WhoCares.exe is the name of this program
var bytes = File.ReadAllBytes(@"WhoCares.exe");

var asm1 = Assembly.Load(bytes);
var asm2 = Assembly.Load(bytes);
var asm3 = Assembly.Load(bytes);

var domainAssemblies = AppDomain.CurrentDomain.GetAssemblies();

foreach (var asm in domainAssemblies)
{
    Console.WriteLine(asm.FullName);
}

And the output:

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
WhoCares, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
WhoCares, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
WhoCares, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
WhoCares, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
Press any key to continue . . .

Is there any risk im having?

There is no Assembly.Unload or AppDomain.UnloadAssembly. You simply can't unload from an AppDomain after loading it. This means you can't free that memory, so each time you're loading the assembly, you're allocating memory you'll never get back. The only way around this would be to load the assembly in a separate AppDomain.

Upvotes: 2

Related Questions