lysergic-acid
lysergic-acid

Reputation: 20050

What is the reason that individual assemblies cannot be unloaded in C#

In C# (or maybe in .NET in general) individual assemblies cannot be unloaded from memory. Unloading can only occur at the AppDomain level.

I am wondering what are there reasons behind this design? Other languages support this feature (C++ i think)

Upvotes: 3

Views: 154

Answers (1)

porges
porges

Reputation: 30580

Here is an MSDN blog post listing some reasons why not. The main issue is:

First off, you are running that code in the app domain (duh!). That means there are potentially call sites and call stacks with addresses in them that are expecting to keep working. Have you ever gotten an access violation where your EIP points to 0x???????? That is an example where someone freed up a DLL, the pages got unmapped by the memory system, and then you tried to branch to it. This typically happens in COM when you have a ref counting error and you make an interface method call. We cannot afford to be as lose with managed code. We must guarantee we know all of the code you are executing and that it is type safe and verifiable. That means explicit tracking of anything that could be using that code, including GC objects and COM interop wrappers. This tracking is handled today around an app domain boundary. Tracking it at the assembly level becomes quite expensive.

I'll summarise this in higher-level language:

Basically, things that go wrong if you simply delete executable code go wrong on the unmanaged level. You would have compiled code that points to other compiled code that is no longer there, so your code would jump into an area that is invalid, and possibly contains arbitrary data.

This is unacceptable in managed code, because things are meant to be safe and have some guarantees around them. One of these guarantees is that your code can't execute arbitrary sections of memory.

To handle this issue properly you'd have to track many more things more closely, and this would be a large overhead. The alternative is to only track these things at appdomain boundaries, which is what is done.

Upvotes: 4

Related Questions