使用AppDomain中加载/卸载外部组​​件 [英] Use AppDomain to load/unload external assemblies

查看:155
本文介绍了使用AppDomain中加载/卸载外部组​​件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况如下:

  • 创建新的AppDomain
  • 在加载某些组件进去
  • 在做一些与魔法加载的DLL
  • 卸载AppDomain中释放内存和放大器;加载的库

下面是code,我想要使用

Below is the code that I'm trying to use

    class Program
{
    static void Main(string[] args)
    {
        Evidence e = new Evidence(AppDomain.CurrentDomain.Evidence);
        AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
        Console.WriteLine("Creating new AppDomain");
        AppDomain newDomain = AppDomain.CreateDomain("newDomain", e, setup);
        string fullName = Assembly.GetExecutingAssembly().FullName;
        Type loaderType = typeof(AssemblyLoader);
        var loader = (AssemblyLoader)newDomain.CreateInstanceFrom(loaderType.Assembly.Location, loaderType.FullName).Unwrap();
        Console.WriteLine("Loading assembly");
        Assembly asm = loader.LoadAssembly("library.dll");
        Console.WriteLine("Creating instance of Class1");
        object instance = Activator.CreateInstance(asm.GetTypes()[0]);
        Console.WriteLine("Created object is of type {0}", instance.GetType());
        Console.ReadLine();
        Console.WriteLine("Unloading AppDomain");
        instance = null;
        AppDomain.Unload(newDomain);
        Console.WriteLine("New Domain unloaded");
        Console.ReadLine();
    }

    public class AssemblyLoader : MarshalByRefObject
    {
        public Assembly LoadAssembly(string path)
        {
            return Assembly.LoadFile(path);
        }
    }
}

library.dll 的仅包括一个虚拟的类,有一个巨大的字符串表(为了便于跟踪内存消耗)

library.dll consists only of a single dummy class, with one huge string table(for easier tracking the memory consumption)

现在的问题是,内存不会真正被释放。更重要的是令人惊讶的,内存使用量实际上AppDomain.Unload后增加()

Now the problem is that memory actually isn't freed. What's more surprising, memory usage actually increases after AppDomain.Unload()

任何人都可以提供一些线索对这个问题?

Can anyone shed some light on this issue?

推荐答案

我已经发布,其中3个不同的组件加载不同的应用领域和卸载成功的例子。这里是链接<一href="http://www.softwareinteractions.com/blog/2010/2/7/loading-and-unloading-net-assemblies.html">http://www.softwareinteractions.com/blog/2010/2/7/loading-and-unloading-net-assemblies.html

I have posted an example where 3 different assemblies are loaded in different app domains and unloaded successfully. Here is the link http://www.softwareinteractions.com/blog/2010/2/7/loading-and-unloading-net-assemblies.html

这篇关于使用AppDomain中加载/卸载外部组​​件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆