.Net6新版本的AssemblyLoadContext 加载程序集和卸载程序集

.Net6新版本的AssemblyLoadContext 加载程序集和卸载程序集

6ff5862469009c7178e175614b8a5780.png
img

准备俩个项目

第一个是控制台

第二个项目是类库

类库项目中只有一个示例class

将类库的代码生成dll

af8a88f22ec86366a80869dc8c1ab668.png
img

并且设置属性为复制到输出目录

using System.Runtime.Loader;

var domain = new AssemblyLoadContext("DomainServer", true);

var assembly = domain.LoadFromAssemblyPath(Path.Combine(AppContext.BaseDirectory, "DomainServer.dll"));

foreach (var context in AssemblyLoadContext.All)
{
 Console.WriteLine("当前存在的程序集:"+context.Name);
}
Console.WriteLine("-------------------------");


domain.Unload();

foreach (var context in AssemblyLoadContext.All)
{
 Console.WriteLine("当前存在的程序集:" + context.Name);
}

Console.ReadKey();

[1d0c180eb08daa16b944df7b7004e1c9.png](javascript:void(0);)

写入代码到Program类中 由于项目使用.Net7创建 所以采用顶级语法 没有main方法

然后执行程序

8e4786eb5f33f818a5ca7e5ee89ade27.png
img

我们看到当加载程序的时候我们的项目中存在了俩个程序集

当前Unload卸载程序集的时候我们项目只存在一个程序集

使用 new AssemblyLoadContext("DomainServer", true); 创建一个AssemblyLoadContext对象

第二个参数 true启用卸载;否则,假的。默认值为false,因为启用卸载会带来性能损失。

这个卸载只会卸载AssemblyLoadContext中加载的所有程序集

我们还可以订阅卸载事件这样就知道那些程序集卸载成功了

using System.Runtime.Loader;

var domain = new AssemblyLoadContext("DomainServer",true);

var assembly = domain.LoadFromAssemblyPath(Path.Combine(AppContext.BaseDirectory, "DomainServer.dll"));

foreach (var context in AssemblyLoadContext.All)
{
    Console.WriteLine("当前存在的程序集:"+context.Name);
}

Console.WriteLine("-------------------------");

domain.Unloading += context =>
{
    Console.WriteLine("当前卸载的程序集:"+string.Join(',', context.Assemblies.Select(x => x.FullName)));
};

domain.Unload();

foreach (var context in AssemblyLoadContext.All)
{
    Console.WriteLine("当前存在的程序集:" + context.Name);
}

Console.ReadKey();

执行效果:

135d6926555dfc5818451236d90700ec.png

注:卸载的前提是引用的对象都被释放!

.Net 6以上版本都可以使用的方法

好了介绍到这里!

技术分享群:737776595

来自 token的分享

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值