• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    .Net core 的热插拔机制的深入探索及卸载问题求救指南

    发布者: 网神之王 | 发布时间: 2025-6-18 08:12| 查看数: 61| 评论数: 0|帖子模式

    一.依赖文件*.deps.json的读取.

    依赖文件内容如下.一般位于编译生成目录中
    1. {
    2. "runtimeTarget": {
    3. "name": ".NETCoreApp,Version=v3.1",
    4. "signature": ""
    5. },
    6. "compilationOptions": {},
    7. "targets": {
    8. ".NETCoreApp,Version=v3.1": {
    9. "PluginSample/1.0.0": {
    10. "dependencies": {
    11. "Microsoft.Extensions.Hosting.Abstractions": "5.0.0-rc.2.20475.5"
    12. },
    13. "runtime": {
    14. "PluginSample.dll": {}
    15. }
    16. },
    17. "Microsoft.Extensions.Configuration.Abstractions/5.0.0-rc.2.20475.5": {
    18. "dependencies": {
    19. "Microsoft.Extensions.Primitives": "5.0.0-rc.2.20475.5"
    20. },
    21. "runtime": {
    22. "lib/netstandard2.0/Microsoft.Extensions.Configuration.Abstractions.dll": {
    23. "assemblyVersion": "5.0.0.0",
    24. "fileVersion": "5.0.20.47505"
    25. }
    26. }
    27. ...
    复制代码
    使用DependencyContextJsonReader加载依赖配置文件源码查看
    1. using (var dependencyFileStream = File.OpenRead("Sample.deps.json"))
    2. {
    3. using (DependencyContextJsonReader dependencyContextJsonReader = new DependencyContextJsonReader())
    4. {
    5. //得到对应的实体文件
    6. var dependencyContext =
    7. dependencyContextJsonReader.Read(dependencyFileStream);
    8. //定义的运行环境,没有,则为全平台运行.
    9. string currentRuntimeIdentifier= dependencyContext.Target.Runtime;
    10. //运行时所需要的dll文件
    11. var assemblyNames= dependencyContext.RuntimeLibraries;
    12. }
    13. }
    复制代码
    二.Net core多平台下RID(RuntimeIdentifier)的定义.

    安装 Microsoft.NETCore.Platforms包,并找到runtime.json运行时定义文件.
    1. {
    2. "runtimes": {
    3. "win-arm64": {
    4. "#import": [
    5. "win"
    6. ]
    7. },
    8. "win-arm64-aot": {
    9. "#import": [
    10. "win-aot",
    11. "win-arm64"
    12. ]
    13. },
    14. "win-x64": {
    15. "#import": [
    16. "win"
    17. ]
    18. },
    19. "win-x64-aot": {
    20. "#import": [
    21. "win-aot",
    22. "win-x64"
    23. ]
    24. },
    25. }
    复制代码
    NET Core RID依赖关系示意图
    1. win7-x64 win7-x86
    2. | \ / |
    3. | win7 |
    4. | | |
    5. win-x64 | win-x86
    6. \ | /
    7. win
    8. |
    9. any
    复制代码
    .Net core常用发布平台RID如下
        
    • windows (win)
    win-x64
    win-x32
    win-arm
        
    • macos (osx)
    osx-x64
        
    • linux (linux)
    linux-x64
    linux-arm
    1. .net core的runtime.json文件由微软提供:查看runtime.json.
    2. runtime.json的runeims节点下,定义了所有的RID字典表以及RID树关系.
    3. 根据*.deps.json依赖文件中的程序集定义RID标识,就可以判断出依赖文件中指向的dll是否能在某一平台运行.
    4. 当程序发布为兼容模式时,我们出可以使用runtime.json文件选择性的加载平台dll并运行.
    三.AssemblyLoadContext的加载原理
    1. public class PluginLoadContext : AssemblyLoadContext
    2. {
    3. private AssemblyDependencyResolver _resolver;
    4. public PluginLoadContext(string pluginFolder, params string[] commonAssemblyFolders) : base(isCollectible: true)
    5. {
    6. this.ResolvingUnmanagedDll += PluginLoadContext_ResolvingUnmanagedDll;
    7. this.Resolving += PluginLoadContext_Resolving;
    8. //第1步,解析des.json文件,并调用Load和LoadUnmanagedDll函数
    9. _resolver = new AssemblyDependencyResolver(pluginFolder);
    10. //第6步,通过第4,5步,解析仍失败的dll会自动尝试调用主程序中的程序集,
    11. //如果失败,则直接抛出程序集无法加载的错误
    12. }
    13. private Assembly PluginLoadContext_Resolving(AssemblyLoadContext assemblyLoadContext, AssemblyName assemblyName)
    14. {
    15. //第4步,Load函数加载程序集失败后,执行的事件
    16. }
    17. private IntPtr PluginLoadContext_ResolvingUnmanagedDll(Assembly assembly, string unmanagedDllName)
    18. {
    19. //第5步,LoadUnmanagedDll加载native dll失败后执行的事件
    20. }
    21. protected override Assembly Load(AssemblyName assemblyName)
    22. {
    23. //第2步,先执行程序集的加载函数
    24. }
    25. protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
    26. {
    27. //第3步,先执行的native dll加载逻辑
    28. }
    29. }
    复制代码
    微软官方示例代码如下:示例具体内容
    1. class PluginLoadContext : AssemblyLoadContext
    2. {
    3. private AssemblyDependencyResolver _resolver;

    4. public PluginLoadContext(string pluginPath)
    5. {
    6. _resolver = new AssemblyDependencyResolver(pluginPath);
    7. }

    8. protected override Assembly Load(AssemblyName assemblyName)
    9. {
    10. string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName);
    11. if (assemblyPath != null)
    12. {
    13. //加载程序集
    14. return LoadFromAssemblyPath(assemblyPath);
    15. }
    16. //返回null,则直接加载主项目程序集
    17. return null;
    18. }

    19. protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
    20. {
    21. string libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
    22. if (libraryPath != null)
    23. {
    24. //加载native dll文件
    25. return LoadUnmanagedDllFromPath(libraryPath);
    26. }
    27. //返回IntPtr.Zero,即null指针.将会加载主项中runtimes文件夹下的dll
    28. return IntPtr.Zero;
    29. }
    30. }
    复制代码
    1. 官方这个示例是有问题的.LoadFromAssemblyPath()函数有bug,
    该函数并不会加载依赖的程序集.正确用法是LoadFormStream()
    2. Load和LoadUnmanagedDll函数实际上是给开发者手动加载程序集使用的,
    自动加载应放到Resolving和ResolvingUnmanagedDll事件中
    原因是,这样的加载顺序不会导致项目的程序集覆盖插件的程序集,造成程序集加载失败.
    3. 手动加载时可以根据deps.json文件定义的runtime加载当前平台下的unmanaged dll文件.
    这些平台相关的dll文件,一般位于发布目录中的runtimes文件夹中.
    四.插件项目一定要和主项目使用同样的运行时.

        
    • 如果主项目是.net core 3.1,插件项目不能选择.net core 2.0等,甚至不能选择.net standard库  
    • 否则会出现不可预知的问题.  
    • 插件是.net standard需要修改项目文件,<TargetFrameworks>netstandard;netcoreapp3.1</TargetFrameworks>  
    • 这样就可以发布为.net core项目.  
    • 若主项目中的nuget包不适合当前平台,则会报Not Support Platform的异常.这时如果主项目是在windows上, 就需要把项目发布目标设置为win-x64.这属于nuget包依赖关系存在错误描述.
    五.AssemblyLoadContext.UnLoad()并不会抛出任何异常.

    当你调用AssemblyLoadContext.UnLoad()卸载完插件以为相关程序集已经释放,那你可能就错了.官方文档表明卸载执行失败会抛出InvalidOperationException,不允许卸载官方说明
    但实际测试中,卸载失败,但并未报错.
    六.反射程序集相关变量的定义为何阻止插件程序集卸载?

    插件
    1. namespace PluginSample
    2. {
    3. public class SimpleService
    4. {
    5. public void Run(string name)
    6. {
    7. Console.WriteLine($"Hello World!");
    8. }
    9. }
    10. }
    复制代码
    加载插件
    1. namespace Test
    2. {
    3. public class PluginLoader
    4. {
    5. pubilc AssemblyLoadContext assemblyLoadContext;
    6. public Assembly assembly;
    7. public Type type;
    8. public MethodInfo method;
    9. public void Load()
    10. {
    11. assemblyLoadContext = new PluginLoadContext("插件文件夹");
    12. assembly = alc.Load(new AssemblyName("PluginSample"));
    13. type = assembly.GetType("PluginSample.SimpleService");
    14. method=type.GetMethod()
    15. }
    16. }
    17. }
    复制代码
    1. 在主项目程序中.AssemblyLoadContext,Assembly,Type,MethodInfo等不能直接定义在任何类中.
    否则在插件卸载时会失败.当时为了测试是否卸载成功,采用手动加载,执行,卸载了1000次,
    发现内存一直上涨,则表示卸载失败.
    2. 参照官方文档后了解了WeakReferece类.使用该类与AssemblyLoadContext关联,当手动GC清理时,
    AssemblyLoadContext就会变为null值,如果没有变为null值则表示卸载失败.
    3. 使用WeakReference关联AssemblyLoadContext并判断是否卸载成功
    1. public void Load(out WeakReference weakReference)
    2. {
    3. var assemblyLoadContext = new PluginLoadContext("插件文件夹");
    4. weakReference = new WeakReference(pluginLoadContext, true);
    5. assemblyLoadContext.UnLoad();
    6. }
    7. public void Check()
    8. {
    9. WeakReference weakReference=null;
    10. Load(out weakReference);
    11. //一般第二次,IsAlive就会变为False,即AssemblyLoadContext卸载失败.
    12. for (int i = 0; weakReference.IsAlive && (i < 10); i++)
    13. {
    14. GC.Collect();
    15. GC.WaitForPendingFinalizers();
    16. }
    17. }
    复制代码
    4. 为了解决以上问题.可以把需要的变量放到静态字典中.在Unload之前把对应的Key值删除掉,即可.
    七.程序集的异步函数执行为何会阻止插件程序的卸载?
    1. public class SimpleService
    2. {
    3. //同步执行,插件卸载成功
    4. public void Run(string name)
    5. {
    6. Console.WriteLine($"Hello {name}!");
    7. }
    8. //异步执行,卸载成功
    9. public Task RunAsync(string name)
    10. {
    11. Console.WriteLine($"Hello {name}!");
    12. return Task.CompletedTask;
    13. }
    14. //异步执行,卸载成功
    15. public Task RunTask(string name)
    16. {
    17. return Task.Run(() => {
    18. Console.WriteLine($"Hello {name}!");
    19. });
    20. }
    21. //异步执行,卸载成功
    22. public Task RunWaitTask(string name)
    23. {
    24. return Task.Run( async ()=> {
    25. while (true)
    26. {
    27. if (CancellationTokenSource.IsCancellationRequested)
    28. {
    29.   break;
    30. }
    31. await Task.Delay(1000);
    32. Console.WriteLine($"Hello {name}!");
    33. }
    34. });
    35. }
    36. //异步执行,卸载成功
    37. public Task RunWaitTaskForCancel(string name, CancellationToken cancellation)
    38. {
    39. return Task.Run(async () => {
    40. while (true)
    41. {
    42. if (cancellation.IsCancellationRequested)
    43. {
    44.   break;
    45. }
    46. await Task.Delay(1000);
    47. Console.WriteLine($"Hello {name}!");
    48. }
    49. });
    50. }
    51. //异步执行,卸载失败
    52. public async Task RunWait(string name)
    53. {
    54. while (true)
    55. {
    56. if (CancellationTokenSource.IsCancellationRequested)
    57. {
    58. break;
    59. }
    60. await Task.Delay(1000);
    61. Console.WriteLine($"Hello {name}!");
    62. }

    63. }
    64. //异步执行,卸载失败
    65. public Task RunWaitNewTask(string name)
    66. {
    67. return Task.Factory.StartNew(async ()=> {
    68. while (true)
    69. {
    70. if (CancellationTokenSource.IsCancellationRequested)
    71. {
    72.   break;
    73. }
    74. await Task.Delay(1000);
    75. Console.WriteLine($"Hello {name}!");
    76. }
    77. },TaskCreationOptions.DenyChildAttach);
    78. }
    79. }
    复制代码
    1. 以上测试可以看出,如果插件调用的是一个常规带wait的async异步函数,则插件一定会卸载失败.
    原因推测是返回的结果是编译器自动生成的状态机实现的,而状态机是在插件中定义的.
    2. 如果在插件中使用Task.Factory.StartNew函数也会调用失败,原因不明.
    官方文档说和Task.Run函数是Task.Factory.StartNew的简单形式,只是参数不同.官方说明
    按照官方提供的默认参数测试,卸载仍然失败.说明这两种方式实现底层应该是不同的.
    八.正确卸载插件的方式

        
    • 任何与插件相关的非局部变量,不能定义在类中,如果想全局调用只能放到Dictionary中,  
    • 在调用插件卸载之前,删除相关键值.  
    • 任何通过插件返回的变量,不能为插件内定义的变量类型.尽量使用json传递参数.  
    • 插件入口函数尽量使用同步函数,如果为异步函数,只能使用Task.Run方式裹所有逻辑.  
    • 如果有任何疑问或不同意见,请赐教.
    NFinal2开源框架。https://git.oschina.net/LucasDot/NFinal2/tree/master
    到此这篇关于.Net core 的热插拔机制的深入探索及卸载问题求救指南的文章就介绍到这了,更多相关.Net core热插拔机制内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    来源:https://www.jb51.net/article/199407.htm
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表