在操作系统中,利用进程可以对正在运行的应用程序进行隔离,每个应用程序被加载到单独的进程中,并为其分配虚拟内存,进程无法直接访问物理内存,只能通过操作系统将虚拟内存映射到物理内存中,并保证进程之间的物理内存不会重叠,但是进程最大的缺点就是效率问题,尤其是进程的切换开销很大,而进程间不能共享内存,所以不可能从一个进程通过传递指针给另一个进程。

在.NET中出现了一个新的概念:AppDomain——应用程序域,所有.NET应用程序都需要运行在托管环境中,操作系统能提供的只有进程,因此.NET程序需要通过AppDomain这个媒介来运行在进程中,同时使用该incheng提供的内存空间,只要是.NET的应用都会运行在某个AppDomain中。

当我们运行一个.NET应用程序或者运行库宿主时,OS会首先建立一个进程,然后会在进程中加载CLR(这个加载一般是通过调用_CorExeMain或者_CorBindToRuntimeEx方法来实现),在加载CLR时会创建一个默认的AppDomain,它是CLR的运行单元,程序的Main方法就是在这里执行,这个默认的AppDomain是唯一且不能被卸载的,当该进程消灭时,默认AppDomain才会随之消失。

一个进程中可以有多个AppDomain,且它们直接是相互隔离的,我们的Assembly是不能单独执行的,它必须被加载到某个AppDomain中,要想卸载一个Assembly就只能卸载其AppDomain。

最近在我所参加的一个项目中要实现这样一个模块:定制一个作业管理器,它可以定时的以不同频率执行某些.Net应用程序或者存储过程,这里的频率可以是仅一次、每天、每周还是每月进行执行计划的实施,对于调用存储过程没什么好说的,但是调用.Net应用程序的时候就需要考虑如下问题:

一旦Assembly被作业管理器的服务器调用,(比如某个执行计划正好要被执行了),在调用之前会将程序集加载到默认AppDomain,然后执行,这就有个问题,如果我需要做替换或者删除Assembly等这些操作的时候,由于Assembly已经被默认AppDomain加载,那么对它的更改肯定是不允许的,它会弹出这样的错误: ,除非你关掉作业管理服务器,然后再操作,显然这样做是很不合理的。

并且默认AppDomain是不能被卸载的,那么我们该怎么办呢,我想到的方法是动态的加载Assembly,新建一个AppDomain,让Assembly加载到这个新AppDomain中然后执行,当执行完后卸载这个新的AppDomain即可,方法如下:

1、创建程序集加载类AssemblyDynamicLoader,该类用来创建新的AppDomain,并生成用来执行.Net程序的RemoteLoader类:

using System;

    using System.Collections.Generic;
    using System.Globalization;
    using System.IO;
    using System.Reflection;
    using System.Text;
    using Ark.Log;

/// <summary>
    /// The local loader.
    /// </summary>
    public class AssemblyDynamicLoader
    {
        /// <summary>
        /// The log util.
        /// </summary>
        private static ILog log = LogManager.GetLogger(typeof(AssemblyDynamicLoader));

/// <summary>
        /// The new appdomain.
        /// </summary>
        private AppDomain appDomain;

/// <summary>
        /// The remote loader.
        /// </summary>
        private RemoteLoader remoteLoader;

/// <summary>
        /// Initializes a new instance of the <see cref="LocalLoader"/> class.
        /// </summary>
        public AssemblyDynamicLoader()
        {
            AppDomainSetup setup = new AppDomainSetup();
            setup.ApplicationName = "ApplicationLoader";
            setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
            setup.PrivateBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "private");
            setup.CachePath = setup.ApplicationBase;
            setup.ShadowCopyFiles = "true";
            setup.ShadowCopyDirectories = setup.ApplicationBase;

this.appDomain = AppDomain.CreateDomain("ApplicationLoaderDomain", null, setup);
            String name = Assembly.GetExecutingAssembly().GetName().FullName;

this.remoteLoader = (RemoteLoader)this.appDomain.CreateInstanceAndUnwrap(name, typeof(RemoteLoader).FullName);
        }

/// <summary>
        /// Invokes the method.
        /// </summary>
        /// <param name="fullName">The full name.</param>
        /// <param name="className">Name of the class.</param>
        /// <param name="argsInput">The args input.</param>
        /// <param name="programName">Name of the program.</param>
        /// <returns>The output of excuting.</returns>
        public String InvokeMethod(String fullName, String className, String argsInput, String programName)
        {
            this.remoteLoader.InvokeMethod(fullName, className, argsInput, programName);
            return this.remoteLoader.Output;
        }

/// <summary>
        /// Unloads this instance.
        /// </summary>
        public void Unload()
        {
            try
            {
                AppDomain.Unload(this.appDomain);
                this.appDomain = null;
            }
            catch (CannotUnloadAppDomainException ex)
            {
                log.Error("To unload assembly error!", ex);
            }
        }
    }

2、创建RemoteLoader类,它可以在AppDomain中自由穿越,这就需要继承System.MarshalByRefObject这个抽象类,这里RemoteLoader如果不继承MarshalByRefObject类则一定会报错(在不同AppDomain间传递对象,该对象必须是可序列化的)。以RemoteLoader类做为代理来调用待执行的.Net程序。

using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.IO;
    using System.Reflection;
    using System.Text;

/// <summary>
    /// The Remote loader.
    /// </summary>
    public class RemoteLoader : MarshalByRefObject
    {
        /// <summary>
        /// The assembly we need.
        /// </summary>
        private Assembly assembly = null;

/// <summary>
        /// The output.
        /// </summary>
        private String output = String.Empty;

/// <summary>
        /// Gets the output.
        /// </summary>
        /// <value>The output.</value>
        public String Output
        {
            get
            {
                return this.output;
            }
        }

/// <summary>
        /// Invokes the method.
        /// </summary>
        /// <param name="fullName">The full name.</param>
        /// <param name="className">Name of the class.</param>
        /// <param name="argsInput">The args input.</param>
        /// <param name="programName">Name of the program.</param>
        public void InvokeMethod(String fullName, String className, String argsInput, String programName)
        {
            this.assembly = null;
            this.output = String.Empty;

try
            {
                this.assembly = Assembly.LoadFrom(fullName);

Type pgmType = null;
                if (this.assembly != null)
                {
                    pgmType = this.assembly.GetType(className, true, true);
                }
                else
                {
                    pgmType = Type.GetType(className, true, true);
                }

Object[] args = RunJob.GetArgs(argsInput);

BindingFlags defaultBinding = BindingFlags.DeclaredOnly | BindingFlags.Public
                        | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase
                        | BindingFlags.InvokeMethod | BindingFlags.Static;

CultureInfo cultureInfo = new CultureInfo("es-ES", false);

try
                {
                    MethodInfo methisInfo = RunJob.GetItsMethodInfo(pgmType, defaultBinding, programName);
                    if (methisInfo == null)
                    {
                        this.output = "EMethod does not exist!";
                    }

if (methisInfo.IsStatic)
                    {
                        if (methisInfo.GetParameters().Length == 0)
                        {
                            if (methisInfo.ReturnType == typeof(void))
                            {
                                pgmType.InvokeMember(programName, defaultBinding, null, null, null, cultureInfo);
                                this.output = "STo call a method without return value successful.";
                            }
                            else
                            {
                                this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, null, null, cultureInfo);
                            }
                        }
                        else
                        {
                            if (methisInfo.ReturnType == typeof(void))
                            {
                                pgmType.InvokeMember(programName, defaultBinding, null, null, args, cultureInfo);
                                this.output = "STo call a method without return value successful.";
                            }
                            else
                            {
                                this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, null, args, cultureInfo);
                            }
                        }
                    }
                    else
                    {
                        if (methisInfo.GetParameters().Length == 0)
                        {
                            object pgmClass = Activator.CreateInstance(pgmType);

if (methisInfo.ReturnType == typeof(void))
                            {
                                pgmType.InvokeMember(programName, defaultBinding, null, pgmClass, null, cultureInfo);
                                this.output = "STo call a method without return value successful.";
                            }
                            else
                            {
                                this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, pgmClass, null, cultureInfo);   //'ymtpgm' is program's name and the return value of it must be started with 'O'.
                            }
                        }
                        else
                        {
                            object pgmClass = Activator.CreateInstance(pgmType);

if (methisInfo.ReturnType == typeof(void))
                            {
                                pgmType.InvokeMember(programName, defaultBinding, null, pgmClass, args, cultureInfo);
                                this.output = "STo call a method without return value successful.";
                            }
                            else
                            {
                                this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, pgmClass, args, cultureInfo);   //'ymtpgm' is program's name and the return value of it must be started with 'O'.
                            }
                        }
                    }
                }
                catch
                {
                    this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, null, null, cultureInfo);
                }
            }
            catch (Exception e)
            {
                this.output = "E" + e.Message;
            }
        }

}

其中的InvokeMethod方法只要提供Assembly的全名、类的全名、待执行方法的输入参数和其全名就可以执行该方法,该方法可以是带参数或不带参数,静态的或者不是静态的。

最后这样使用这两个类:

AssemblyDynamicLoader loader = new AssemblyDynamicLoader();
String output = loader.InvokeMethod("fileName", "ymtcla", "yjoinp", "ymtpgm");

loader.Unload();

转载于:https://www.cnblogs.com/vivounicorn/archive/2009/06/24/1510297.html

关于C#中动态加载AppDomain的问题相关推荐

  1. 在.Net framework中动态加载Assembly的loadFromRemoteSources配置

    简介 在插件类型的应用开发中,我们可能会在程序中动态加载一个assembly文件,创建其中的类对象并使用. 这时,就涉及到了CAS(code access security)和信任沙盒. 一般,我们的 ...

  2. 在VC中动态加载ODBC的方法

    在VC中动态加载ODBC的方法     在使用VC.VB.Delphi等高级语言编写数据库应用程序时,往往需要用户自己在控制面板中配置ODBC数据源.对于一般用户而言,配置ODBC数据源可能是一件比较 ...

  3. Node.js项目中动态加载环境变量配置

    NODE_MODULES:项目中动态加载环境变量配置 开始 在平时的 Node.js 项目开发中,我们需要在项目中添加各种各样的配置:服务端口.服务地址.图片上传.数据库.Redis 等等. 通常情况 ...

  4. bpl文件java,在LoadLibrary中动态加载BPL失败

    我想在Delphi 10 Seattle(Update 1)或Delphi 10.1 Berlin项目(Enterprise版本)中动态加载BPL模块 . 但LoadPackage函数失败并显示消息( ...

  5. Java中动态加载字节码的方法 (持续补充)

    文章目录 Java中动态加载字节码的方法 1.利用 URLClassLoader 加载远程class文件 2.利用 ClassLoader#defineClass 直接加载字节码 2.1 类加载 - ...

  6. python requests 动态加载_Python获取网页中动态加载的数据

    Python获取网页中动态加载的数据 0.XHR 是什么? XHR是 XMLHttpRequest 对象.既Ajax功能实现所依赖的对象,在JQuery中的Ajax是对 XHR的封装. 1.查看异步加 ...

  7. C#中动态加载和卸载DLL

    在C++中加载和卸载DLL是一件很容易的事,LoadLibrary和FreeLibrary让你能够轻易的在程序中加载DLL,然后在任何地方卸载.在C#中我们也能使用Assembly.LoadFile实 ...

  8. C#中动态加载卸载类库

    网上现有很多的文章是介绍怎样开发插件化的框架的,大部分无非是用Assembly.load等方法,动态加载类库,但这种方法有个缺点,就是没有办法卸载,因为net中就没有提供卸载assembly的方法,还 ...

  9. uni中动态加载class_SpringBoot中使用LoadTimeWeaving技术实现AOP功能

    1. 关于LoadTimeWeaving 1.1 LTW与不同的切面织入时机 AOP--面向切面编程,通过为目标类织入切面的方式,实现对目标类功能的增强.按切面被织如到目标类中的时间划分,主要有以下几 ...

  10. javascript中动态加载js、vbs脚本或者css样式表

    目录:DynamicLoad类简介.属性.方法.事件.示例.下载. DynamicLoad类简介 本文将为您介绍一个在javascript中可以动态加载js.vbs脚本和css样式表的DynamicL ...

最新文章

  1. RestTemplate--解决中文乱码
  2. LeetCode 编程 二
  3. 《算法竞赛入门经典》计算组合数问题
  4. role cache - set data user parameter - /UI2/CACHE_DISABLE
  5. 判断对象是否为数组/函数
  6. 2021全国大学生电子设计竞赛论文(智能送药小车(F题))(电赛论文模板)
  7. excel两个表格数据对比_常简单又实用的Excel数据对比技巧
  8. 地学计算方法/地统计学(第四章变异函数理论模型)
  9. 计算机乱七八糟小知识备忘录
  10. ggplot2-数据关系型图表
  11. mysql连接耗尽_连接池耗尽了!!!
  12. 学习R语言编程——常用算法——导数与微积分的近似计算
  13. 2020年全球数据中心十大发展趋势
  14. 【云计算】弹性公网IP
  15. 2017年最受欢迎的十篇神秘的程序员漫画
  16. 游戏代理平台一天结一次靠谱吗?
  17. ChatGPT为什么可以取代那么多职位?
  18. ip组播,IGMP协议,PIM协议
  19. JWT 实现登录认证 + Token 自动续期方案
  20. 风铃发卡网源码最新版-可商用,支持个人码支付,当面付

热门文章

  1. django数据库操作
  2. 027.3 反射技术 简单应用
  3. JavaScript技巧总结和本地存储(一)
  4. 20155226-虚拟机与Linux之初体验
  5. 函数对象function object 以及boost::bind的一点了解
  6. .net c#购物车模块分析
  7. windows 域名+虚拟目录 (php)
  8. 守护进程-----杀死自己的进程再重新启动自己
  9. HDU 2457 DNA repair(AC自动机 + DP)题解
  10. 软件工程--结对第二次作业