无法在C#中卸载单个程序集的原因是什么

提问

在C#中(或通常在.NET中),无法从内存中卸载单个程序集.
只能在AppDomain级别上进行卸载.

我想知道这种设计背后的原因是什么?其他语言支持此功能(我认为)

最佳答案

Here is an MSDN blog post列出了为什么不列出的一些原因.主要问题是:

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.

我将用高级语言对此进行总结:

基本上,如果仅删除可执行代码,就会在非托管级别上出错.您将拥有指向不再存在的其他已编译代码的已编译代码,因此您的代码将跳入无效区域,并可能包含任意数据.

这在托管代码中是不可接受的,因为事物本来就是安全的并且周围有一些保证.这些保证之一是您的代码无法执行内存的任意部分.

要正确处理此问题,您必须更紧密地跟踪更多事情,这将是一笔巨大的开销.另一种方法是仅在应用程序域边界跟踪这些操作,这是完成的操作.

评论