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

文章插图
准备俩个项目
第一个是控制台
第二个项目是类库
类库项目中只有一个示例class
将类库的代码生成dll

文章插图
并且设置属性为复制到输出目录
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();
写入代码到Program类中 由于项目使用.net7创建 所以采用顶级语法 没有main方法
然后执行程序

文章插图
我们看到当加载程序的时候我们的项目中存在了俩个程序集
当前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();执行效果:

文章插图
好了介绍到这里!
【.Net6新版本的AssemblyLoadContext 加载程序集和卸载程序集】
经验总结扩展阅读
- 2022年12月生子最好的吉日老黄历 2022年12月几号生子最合适
- 带你了解NLP的词嵌入
- OMG这是俺的baby是什么梗
- 2022温馨的结婚祝福语
- 2023高考成绩查询时间及入口
- MySQL数据库的性能分析 ---图书《软件性能测试分析与调优实践之路》-手稿节选
- 如何通过Java导出带格式的 Excel 数据到 Word 表格
- 2023高考成绩什么时候公布
- 百度网盘会员到期后超过的文件会怎样
- 2023年1月14日北小年是出行吉日吗