zoukankan      html  css  js  c++  java
  • C#中运用AppDomain动态加载程序集详解

      在.net中有了一个AppDomain——应用程序域的新概念,.NET程序通过AppDomain这个媒介来运行在进程中。

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

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

      一旦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;
    ///  
    /// The local loader. 
    ///  
    public class AssemblyDynamicLoader
    {
        
    ///  
        
    /// The log util. 
        
    ///  
        private static ILog log = LogManager.GetLogger(typeof(AssemblyDynamicLoader));
        
    ///  
        
    /// The new appdomain. 
        
    ///  
        private AppDomain appDomain;
        
    ///  
        
    /// The remote loader. 
        
    ///  
        private RemoteLoader remoteLoader;
        
    ///  
        
    /// Initializes a new instance of the  class. 
        
    ///  
        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);
        }
        
    ///  
        
    /// Invokes the method. 
        
    ///  
        
    /// The full name. 
        
    /// Name of the class. 
        
    /// The args input. 
        
    /// Name of the program. 
        
    /// The output of excuting. 
        public String InvokeMethod(String fullName, String className,         String argsInput, String programName)
        {
            
    this.remoteLoader.InvokeMethod(fullName, className, argsInput, programName);
            
    return this.remoteLoader.Output;
        }
        
    ///  
        
    /// Unloads this instance. 
        
    ///  
        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;
    ///  
    /// The Remote loader. 
    ///  
    public class RemoteLoader : MarshalByRefObject
    {
        
    ///  
        
    /// The assembly we need. 
        
    ///  
        private Assembly assembly = null;
        
    ///  
        
    /// The output. 
        
    ///  
        private String output = String.Empty;
        
    ///  
        
    /// Gets the output. 
        
    ///  
        
    /// The output. 
        public String Output
        {
            
    get
            {
                
    return this.output;
            }
        }
        
    ///  
        
    /// Invokes the method. 
        
    ///  
        
    /// The full name. 
        
    /// Name of the class. 
        
    /// The args input. 
        
    /// Name of the program. 
        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, truetrue);
                }
                
    else
                {
                    pgmType 
    = Type.GetType(className, truetrue);
                }
                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,
                                    
    nullnullnull, cultureInfo);
                                
    this.output = "STo call a method without return value successful.";
                            }
                            
    else
                            {
                                
    this.output = (String)pgmType.InvokeMember(programName,
                                    defaultBinding, 
    nullnullnull, cultureInfo);
                            }
                        }
                        
    else
                        {
                            
    if (methisInfo.ReturnType == typeof(void))
                            {
                                pgmType.InvokeMember(programName, defaultBinding,
                                    
    nullnull, args, cultureInfo);
                                
    this.output = "STo call a method without return value successful.";
                            }
                            
    else
                            {
                                
    this.output = (String)pgmType.InvokeMember(programName, 
                                    defaultBinding, 
    nullnull, 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, 
    nullnullnull, 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();


     

  • 相关阅读:
    最强神作!Crysis深度剖析与优化指南(1825)
    到底什么样的一款游戏就算全3D?
    [转贴]因父之名:一个“非科班”的成长史
    转载《阅读一款3D引擎的方法备忘》
    魔兽世界角色换装
    Flash游戏开发之按键控制(复合键,八方向键)
    通过MC里的按钮跳转场景
    Cuyahoga 的安装
    如何从数组中随机取出多个不重复的项
    [Flash开发笔记] flash 8 中的 setTimeout()
  • 原文地址:https://www.cnblogs.com/kenter/p/2003912.html
Copyright © 2011-2022 走看看