博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#中运用AppDomain动态加载程序集详解
阅读量:4116 次
发布时间:2019-05-25

本文共 11287 字,大约阅读时间需要 37 分钟。

在.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加载,那么对它的更改肯定是不允许的,它会弹出这样的错误:

无法删除WindowsApplication1: 访问被拒绝

请确定磁盘末被写保护
而且文件末被使用

除非你关掉作业管理服务器,然后再操作,显然这样做是很不合理的。

  并且默认AppDomain是不能被卸载的,那么我们该怎么办呢,我想到的方法是动态的加载Assembly,新建一个AppDomain,让Assembly加载到这个新AppDomain中然后执行,当执行完后卸载这个新的AppDomain即可。核心思想就是:如果程序集被加载到默认应用程序域中,则当进程运行时将无法从内存中卸载该程序集。但是,如果打开另一个应用程序域来加载和执行程序集,则卸载该应用程序域时也会同时卸载程序集。使用此技术最小化长时间运行的进程的工作集。,方法如下:

 

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

 

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->  
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程序。

 

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->  
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,
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的全名、类的全名、待执行方法的输入参数和其全名就可以执行该方法,该方法可以是带参数或不带参数,静态的或者不是静态的。

  最后这样使用这两个类:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->  
  AssemblyDynamicLoader loader 
=
 
new
 AssemblyDynamicLoader();  String output 
=
 loader.InvokeMethod(
"
fileName
"
, 
"
ymtcla
"
, 
"
yjoinp
"
, 
"
ymtpgm
"
);  loader.Unload();

转载地址:http://kjupi.baihongyu.com/

你可能感兴趣的文章
Day_15JavaSE 异常
查看>>
异常 Java学习Day_15
查看>>
JavaSE_day_03 方法
查看>>
day-03JavaSE_循环
查看>>
Mysql初始化的命令
查看>>
day_21_0817_Mysql
查看>>
day-22 mysql_SQL 结构化查询语言
查看>>
MySQL关键字的些许问题
查看>>
浅谈HTML
查看>>
css基础
查看>>
HTML&CSS进阶
查看>>
Servlet进阶和JSP基础
查看>>
servlet中的cookie和session
查看>>
过滤器及JSP九大隐式对象
查看>>
软件(项目)的分层
查看>>
菜单树
查看>>
MySQL-分布式架构-MyCAT
查看>>
设计模式六大原则(6):开闭原则
查看>>
阿里面试总结--JAVA
查看>>
Servlet的生命周期
查看>>