繁体   English   中英

使用AppDomain加载/卸载外部程序集

[英]Use AppDomain to load/unload external assemblies

我的情况如下:

  • 创建新的AppDomain
  • 将一些程序集加载到其中
  • 用已加载的dll做一些魔术
  • 卸载AppDomain以释放内存和已加载的库

以下是我尝试使用的代码

    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仅包含一个虚拟类,带有一个巨大的字符串表(以便更轻松地跟踪内存消耗)

现在的问题是内存实际上没有被释放。 更令人惊讶的是,在AppDomain.Unload()之后,内存使用实际上增加了

谁能阐明这个问题?

这不是一个完整的答案:我只是注意到您使用字符串作为有效负载。 字符串对此没有用,因为文字字符串是固定的。 实习字符串在AppDomain之间共享,因此在卸载AppDomain时不会卸载该部分。 尝试改用byte []。

回答我自己的问题-不知道在StackOverflow上是否有更好的方法...如果有,我将不胜感激... 。 下面的代码,如果有人发现任何弱点-请回复。

class Program
{
    static void Main(string[] args)
    {
        Console.ReadLine();
        for(int i=0;i<10;i++)
        {
            AppDomain appDomain = AppDomain.CreateDomain("MyTemp");
            appDomain.DoCallBack(loadAssembly);
            appDomain.DomainUnload += appDomain_DomainUnload;

            AppDomain.Unload(appDomain);        
        }

        AppDomain appDomain2 = AppDomain.CreateDomain("MyTemp2");
        appDomain2.DoCallBack(loadAssembly);
        appDomain2.DomainUnload += appDomain_DomainUnload;

        AppDomain.Unload(appDomain2);

        GC.Collect();
        GC.WaitForPendingFinalizers();  
        Console.ReadLine();
    }

    private static void loadAssembly()
    {
        string fullPath = @"E:\tmp\sandbox\AppDomains\AppDomains1\AppDomains1\bin\Debug\BigLib.dll";
        var assembly = Assembly.LoadFrom(fullPath);
        var instance = Activator.CreateInstance(assembly.GetTypes()[0]);
        Console.WriteLine("Creating instance of {0}", instance.GetType());
        Thread.Sleep(2000);
        instance = null;
    }

    private static void appDomain_DomainUnload(object sender, EventArgs e)
    {
        AppDomain ap = sender as AppDomain;
        Console.WriteLine("Unloading {0} AppDomain", ap.FriendlyName);
    }
}

我已经发布了一个示例,其中3个不同的程序集分别在不同的应用程序域中加载并成功卸载。 这是链接http://www.softwareinteractions.com/blog/2010/2/7/loading-and-unloading-net-assemblies.html

这是一个较晚的答案,但是值得在这里获得对该问题的任何将来看法。 我需要以动态代码编译/执行的方式实现与此类似的功能。 最好的方法是在单独的域(即远程域)中执行所有方法,而不是在主AppDomain中执行,否则应用程序的内存将始终不断增加。 您可以通过远程接口和代理解决此问题。 因此,您可以通过一个接口公开您的方法,该接口将在您的主AppDomain中获得一个实例,然后在远程域中远程执行这些方法,卸载新创建的域(远程域),使其无效,然后强制GC进行收集未使用的对象。 我花了很长时间调试我的代码,直到我不得不强迫GC这样做才行,这一切都很好。 我的实现大部分来自以下网址http : //www.west-wind.com/presentations/dynamicCode/DynamicCode.htm

      //pseudo code
      object ExecuteCodeDynamically(string code)
       {
        Create AppDomain my_app
         src_code = "using System; using System.Reflection; using RemoteLoader;
        namespace MyNameSpace{
       public class MyClass:MarshalByRefObject, IRemoteIterface
      {
      public object Invoke(string local_method, object[] parameters)
        {
       return this.GetType().InvokeMember(local_method, BindingFlags.InvokeMethod, null, this,    parameters);
     }
     public object ExecuteDynamicCode(params object[] parameters)
     {
    " + code + } } } ";// this whole big string is the remote application

     //compile this code which is src_code
     //output it as a DLL on the disk rather than in memory with the name e.g.: DynamicHelper.dll. This can be done by playing with the CompileParameters
     // create the factory class in the secondary app-domain
               RemoteLoader.RemoteLoaderFactory factory =
                  (RemoteLoader.RemoteLoaderFactory)loAppDomain.CreateInstance("RemoteLoader",
                  "RemoteLoader.RemoteLoaderFactory").Unwrap();

            // with the help of this factory, we can now create a real instance
            object loObject = factory.CreateInstance("DynamicHelper.dll", "MyNamespace.MyClass", null);

            // *** Cast the object to the remote interface to avoid loading type info
            RemoteLoader.IRemoteInterface loRemote = (RemoteLoader.IRemoteInterface)loObject;

            if (loObject == null)
            {
                System.Windows.Forms.MessageBox.Show("Couldn't load class.");
                return null;
            }

            object[] loCodeParms = new object[1];
            loCodeParms[0] = "bla bla bla";

            try
            {
                // *** Indirectly call the remote interface
                object result = loRemote.Invoke("ExecuteDynamicCode", loCodeParms);// this is the object to return                

            }
            catch (Exception loError)
            {
                System.Windows.Forms.MessageBox.Show(loError.Message, "Compiler Demo",
                    System.Windows.Forms.MessageBoxButtons.OK,
                    System.Windows.Forms.MessageBoxIcon.Information);
                return null;
            }

            loRemote = null;
            try { AppDomain.Unload(my_app); }
            catch (CannotUnloadAppDomainException ex)
            { String str = ex.Message; }
            loAppDomain = null;
            GC.Collect();//this will do the trick and free the memory
            GC.WaitForPendingFinalizers();
            System.IO.File.Delete("ConductorDynamicHelper.dll");
            return result;

}

请注意,RemoteLoader是应该已经创建并添加到您的主应用程序和远程应用程序中的另一个DLL。 它基本上是一个接口和一个工厂加载程序。 以下代码取自上述网站:

      /// <summary>
    /// Interface that can be run over the remote AppDomain boundary.
   /// </summary>
     public interface IRemoteInterface
     {
    object Invoke(string lcMethod,object[] Parameters);
     }


     naemspace RemoteLoader{
   /// <summary>
   /// Factory class to create objects exposing IRemoteInterface
  /// </summary>
  public class RemoteLoaderFactory : MarshalByRefObject
 {
   private const BindingFlags bfi = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;

 public RemoteLoaderFactory() {}

 /// <summary> Factory method to create an instance of the type whose name is specified,
  /// using the named assembly file and the constructor that best matches the specified parameters.  </summary>
 /// <param name="assemblyFile"> The name of a file that contains an assembly where the type named typeName is sought. </param>
 /// <param name="typeName"> The name of the preferred type. </param>
 /// <param name="constructArgs"> An array of arguments that match in number, order, and type the parameters of the constructor to invoke, or null for default constructor. </param>
 /// <returns> The return value is the created object represented as ILiveInterface. </returns>
 public IRemoteInterface Create( string assemblyFile, string typeName, object[] constructArgs )
 {
  return (IRemoteInterface) Activator.CreateInstanceFrom(
  assemblyFile, typeName, false, bfi, null, constructArgs,
  null, null, null ).Unwrap();
   }
  }
  }

希望这有意义并能帮助...

.Net使用不确定的终结处理。 如果您想查看内存是否下降,则应该...

GC.Collect(); 
GC.WaitForPendingFinalizers();

...卸载后。 另外,除非需要强制收集(而不是不太可能),否则应允许系统自行收集。 通常,如果您认为需要在生产代码中强制进行收集,则存在资源泄漏,通常是由于未在IDisposable对象上调用Dispose或未释放非托管对象引起的

using (var imdisposable = new IDisposable())
{
}
//
var imdisposable = new IDisposable();
imdisposable.Dispose();
//
Marshal.Release(intPtr); 
//
Marshal.ReleaseComObject(comObject);

每个程序集也被加载到主域中。 由于使用的是Assembly实例,因此您的主域将加载此程序集,以便能够分析其中的所有类型。

如果要防止在两个域中加载程序集,请使用AppDomain.CreateInstance方法。

实际上,以上答案的组合为我指出了(我希望)正确答案:我的代码如下:

AppDomain newDomain = AppDomain.CreateDomain("newDomain", e, setup);
string fullName = Assembly.GetExecutingAssembly().FullName;
Type loaderType = typeof(AssemblyLoader);
FileStream fs = new FileStream(@"library.dll", FileMode.Open);
byte[] buffer = new byte[(int)fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();

Assembly domainLoaded = newDomain.Load(buffer);
object loaded = Activator.CreateInstance(domainLoaded.GetTypes()[1]);
AppDomain.Unload(newDomain);
GC.Collect();
GC.WaitForPendingFinalizers();

我不能使用AppDomain.CreateInstance,因为它需要我不知道的Assembly.FullName-库是动态加载的。

感谢您的帮助,Bolek。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM