温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#中AppDomain的作用是什么

发布时间:2021-02-03 13:25:10 来源:亿速云 阅读:317 作者:Leah 栏目:开发技术

这期内容当中小编将会给大家带来有关C#中AppDomain的作用是什么,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

基本概念

应用程序域为安全性、可靠性、版本控制以及卸载程序集提供了隔离边界。 应用程序域通常由运行时宿主创建,运行时宿主负责在运行应用程序之前引导公共语言运行时。

应用程序域所提供的隔离具有以下优点:

(1)在一个应用程序中出现的错误不会影响其他应用程序。 因为类型安全的代码不会导致内存错误,所以使用应用程序域可以确保在一个域中运行的代码不会影响进程中的其他应用程序。

(2)能够在不停止整个进程的情况下停止单个应用程序。 使用应用程序域使您可以卸载在单个应用程序中运行的

注意:不能卸载单个程序集或类型。只能卸载整个域。

一切的根源,都是因为只有 Assembly.Load 方法,而没有 Assembly.Unload 方法,只能卸载其所在的 AppDomain。

实践

1. 首先准备一个控制台小程序

操作为读取配置文件(为测试 AppDomain 中配置文件的读取情况),并使用 Newtonsoft.Json 将其序列化为 json(为测试 AppDomain 中加载程序中的第三方引用情况),在控制台输出。项目名为 ReadPrint, 将其编译为 exe 文件,并存放在 D:\AppDomainModules 中。

using Newtonsoft.Json;

using System;
using System.Configuration;

namespace ReadPrint
{
  class Program
  {
    static void Main(string[] args)
    {
      DoSomething();
    }

    public static void DoSomething()
    {
      Person person = new Person
      {
        Account = ConfigurationManager.AppSettings["Account"],
        Name = ConfigurationManager.AppSettings["Name"],
        Age = int.Parse(ConfigurationManager.AppSettings["Age"])
      };

      Console.WriteLine(JsonConvert.SerializeObject(person));
      Console.ReadLine();
    }

    class Person
    {
      public string Account { get; set; }
      public string Name { get; set; }
      public int Age { get; set; }
    }
  }
}

为了查看方便定义了 DoSomething 来执行相关方法。也可以直接写在 Main 方法中,调用时需要传入参数 args。因为最终测试 AppDomain 的程序也打算使用控制台应用,也使用控制台应用来写这个小程序。

2. 编写使用 AppDomain 的程序

主要包含 AssemblyLoader.cs 文件用于封装使用细节,和 Program.cs 主程序文件。

AssemblyLoader.cs

using System;
using System.IO;
using System.Reflection;

namespace AppDomainTest
{
  public class AssemblyDynamicLoader
  {
    private AppDomain appDomain;
    public readonly RemoteLoader remoteLoader;
    public AssemblyDynamicLoader()
    {
      AppDomainSetup setup = new AppDomainSetup();
      setup.ApplicationName = "ApplicationLoader";
      setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
      setup.PrivateBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules");
      setup.CachePath = setup.ApplicationBase;
      setup.ShadowCopyFiles = "true";	# 重点
      setup.ShadowCopyDirectories = setup.ApplicationBase;
      setup.ConfigurationFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules", "ReadPrint.exe.config");
      //AppDomain.CurrentDomain.SetShadowCopyFiles();
      this.appDomain = AppDomain.CreateDomain("ApplicationLoaderDomain", null, setup);
      String name = Assembly.GetExecutingAssembly().GetName().FullName;
      this.remoteLoader = (RemoteLoader)this.appDomain.CreateInstanceAndUnwrap(name, typeof(RemoteLoader).FullName);	# 重点
    }

    public void Unload()
    {
      try
      {
        if (appDomain == null) return;
        AppDomain.Unload(this.appDomain);
        this.appDomain = null;
      }
      catch (CannotUnloadAppDomainException ex)
      {
        throw ex;
      }
    }
  }

  public class RemoteLoader : MarshalByRefObject
  {
    private Assembly _assembly;

    public void LoadAssembly(string assemblyFile)
    {
      try
      {
        _assembly = Assembly.LoadFrom(assemblyFile);
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }

    public void ExecuteMothod(string typeName, string methodName)
    {
      if (_assembly == null)
      {
        return;
      } 
      var type = _assembly.GetType(typeName);
      type.GetMethod(methodName).Invoke(Activator.CreateInstance(type), new object[] { });
    }
  }
}

其中类 RemoteLoader 为加载程序集的类,AssemblyDynamicLoader 类在此基础上封装了新建 AppDomain 的细节。

在 AssemblyDynamicLoader 的构造函数中,为了测试方便,硬编码了一些内容,如 程序集文件查找路径 PrivateBinPath 为当前程序执行目录下面的 Modules 目录,配置文件 ConfigurationFile 为 Modules 目录中的 ReadPrint.exe.config, 以及创建新 AppDomain 时的程序集名称。

AppDomainSetup 的属性 ShadowCopyFiles(似乎可以译为“卷影复制”) 代表是否锁定读取的程序集。如果设置为 true,则将程序集读取至内存,不锁定其文件,这也是热更新的前提;否则在程序执行期间这些程序集文件会被锁定,不能变化。

AppDomain 的方法 CreateInstanceAndUnwrap 意为在 AppDomain 的实例中创建指定类型的新实例,并返回。

在 RemoteLoader 的 ExecuteMethod 中,传入的参数硬编码为空。在实际使用时应当根据实际传入参数。

Program.cs

using System;
using System.IO;

namespace AppDomainTest
{
  class Program
  {
    static void Main(string[] args)
    {
      string modulesPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules");
      DirectoryInfo di = new DirectoryInfo(modulesPath);
      if (!di.Exists)
      {
        di.Create();
      }

      string remotePath = @"D:\AppDomainModules\";

      string[] fileNames = new string[] { "ReadPrint.exe", "Newtonsoft.Json.dll", "ReadPrint.exe.config" };
      foreach(var fileName in fileNames)
      {
        FileInfo fi = new FileInfo(Path.Combine(remotePath, fileName));
        fi.CopyTo(Path.Combine(modulesPath, fileName), true);
      }

      AssemblyDynamicLoader adl = new AssemblyDynamicLoader();
      adl.remoteLoader.LoadAssembly(Path.Combine(modulesPath, "ReadPrint.exe"));
      adl.remoteLoader.ExecuteMethod("ReadPrint.Program", "DoSomething");
      adl.Unload();
    }
  }
}

在主程序文件中,创建 Modules 文件夹,拷贝程序文件、库文件和配置文件。程序运行结果:

C#中AppDomain的作用是什么

可以看到成功调用了我们定义的 DoSomething 方法。

一些思考

1. 为什么不使用 AppDomain 实例的 Load 方法加载程序集

使用此方法,会首先在主程序的 AppDomain 中加载一遍程序集(和依赖),再移至我们创建的 AppDomain 中(特别注意,此时不会从我们新建的 AppDomain 的 PrivateBinPath 中搜索和加载)。

缺点有二,一是随着程序的运行,可能会加载大量的程序集,因此主程序的 AppDomain 也要加载大量程序集,而程序集无法单独卸载,只有在主程序停止后才会卸载,其间必然越积越多,极不优雅;二是无法自定目录,主程序加载程序集和依赖时只会在其指定的 PrivateBinPath 中搜索,因此其它模块所有需要的程序集文件都堆积在同一个目录中,条理不清。

验证
修改 AssemblyDynamicLoader.cs 中的代码,改为直接在构造函数里面执行程序加载,其它不变,并查看我们新建的 AppDomain 中已加载的程序集:

	  //String name = Assembly.GetExecutingAssembly().GetName().FullName;
      //this.remoteLoader = (RemoteLoader)this.appDomain.CreateInstanceAndUnwrap(name, typeof(RemoteLoader).FullName);

      Assembly assembly = this.appDomain.Load("ReadPrint");
      Type t = assembly.GetType("ReadPrint.Program");
      MethodInfo mi = t.GetMethod("DoSomething");
      //mi.Invoke(Activator.CreateInstance(t), new object[] { });

      var tmp = this.appDomain.GetAssemblies();

此处最为奇怪的是,尽管我们在上面指定了自己 AppDomain 的 PrivateBinPath 和 配置文件,执行时依然找的是主程序的 PrivateBinPath 和 配置文件,因此将执行的那一行代码注释。

修改 Program.cs 中的代码,改为仅调用 AssemblyDynamicLoader 的构造函数,其它不变,并查看主程序 AppDomain 中已加载的程序集:

	  AssemblyDynamicLoader adl = new AssemblyDynamicLoader();
      //adl.remoteLoader.LoadAssembly(Path.Combine(modulesPath, "ReadPrint.exe"));
      //adl.remoteLoader.ExecuteMethod("ReadPrint.Program", "DoSomething");
      //adl.Unload();

      var tmp = AppDomain.CurrentDomain.GetAssemblies();

      Console.ReadLine();

结果如图所示:

C#中AppDomain的作用是什么

2. 为什么要使用类似于代理的类 RemoteLoader, 而不直接使用 CreateInstanceAndUnwrap 创建加载进来程序集的实例
直接使用会提示如下错误:

C#中AppDomain的作用是什么

需要注意的是,RemoteLoader 类继承了 MarshalByRefObject,而继承此类的应用可以跨 AppDomain 使用。此处猜测虽然可以在主程序中创建新的 AppDomain,但新的 AppDomain 依然无法完全摆脱主程序。

上述就是小编为大家分享的C#中AppDomain的作用是什么了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI