您的位置:首页 > 编程语言 > C#

《C#高级编程》读书笔记(十三):应用程序域

2016-07-28 15:01 375 查看
在.NET之前的技术中,进程作为独立的边界来使用,每个进程都有其私有的虚拟内存;运行在一个进程的应用程序不能写入另一个应用程序的内存,也不会因为这种方式破坏其他应用程序。该进程用作应用程序之间的一个独立而安全的边界。.NET体系结构应用程序有一个新的边界:应用程序域。使用托管IL代码,运行库可以确保在同一个进程中程序不能访问另一个应用程序的内存。多个应用程序可以运行在一个进程的多个应用程序域中。

AppDomain类用于创建和终止应用程序域,加载、卸载程序集和类型,以及枚举应用程序域中的程序集和线程。

1,ExcuteAssembly()方法

首先,创建一个C#控制台应用程序AssemblyA

using System;

namespace AssemblyA
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"Main in domain {AppDomain.CurrentDomain.FriendlyName} called");
}
}

public class Demo
{
public Demo(int val1, int val2)
{
Console.WriteLine($"Constructor with the values {val1},{val2} in domain " +
$"{AppDomain.CurrentDomain.FriendlyName} called");
}

}
}


运行:Main in domain AssemblyA.exe called

然后创建第二个应用程序AssemblyB.exe

using System;

namespace AssemblyB
{
class Program
{
static void Main(string[] args)
{
AppDomain currentDomain = AppDomain.CurrentDomain;
Console.WriteLine(currentDomain.FriendlyName);
AppDomain seconDomain = AppDomain.CreateDomain("New AppDomain");
seconDomain.ExecuteAssembly("AssemblyA.exe");
//seconDomain.CreateInstance("AssemblyA", "AssemblyA.Demo", true,BindingFlags.CreateInstance, null,new object[] {7,3},null,null );
}
}
}


运行:

AssemblyB.exe
Main in domain New AppDomain called

2,CreateInstance()方法

可以用CreateInstance()方法替代ExcuteAssembly()方法,它的第一个参数是程序集名AssemblyA,第二个参数定义了应实例化的类型AssemblyA.Demo,第三个参数true表示不区分大小写。System.Reflection.BindingFlags.CreateInstance是一个绑定的标志枚举值,用来指定调用的构造函数:

seconDomain.CreateInstance("AssemblyA", "AssemblyA.Demo", true,BindingFlags.CreateInstance, null,new object[] {7,3},null,null );


运行:

AssemblyB.exe
Constructor with the values 7,3 in domain New AppDomain called
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: