一般情况下,一个 .net 程序集加载到程序中以后,它的类型信息以及原生代码等数据会一直保留在内存中,.net 运行时无法回收它们,如果我们要实现插件热加载 (例如 razor 或 aspx 模版的热更新) 则会造成内存泄漏。在以往,我们可以使用 .net framework 的 appdomain 机制,或者使用解释器 (有一定的性能损失),或者在编译一定次数以后重启程序 (asp.net 的 numrecompilesbeforeapprestart) 来避免内存泄漏。
因为 .net core 不像 .net framework 一样支持动态创建与卸载 appdomain,所以一直都没有好的方法实现插件热加载,好消息是,.net core 从 3.0 开始支持了可回收程序集 (collectible assembly),我们可以创建一个可回收的 assemblyloadcontext,用它来加载与卸载程序集。关于 assemblyloadcontext 的介绍与实现原理可以参考 与 。
本文会通过一个 180 行左右的示例程序,介绍如何使用 .net core 3.0 的 assemblyloadcontext 实现插件热加载,程序同时使用了 roslyn 实现动态编译,最终效果是改动插件代码后可以自动更新到正在运行的程序当中,并且不会造成内存泄漏。
首先我们来看看完整源代码与文件夹结构,源代码分为两部分,一部分是宿主,负责编译与加载插件,另一部分则是插件,后面会对源代码的各个部分作出详细讲解。
文件夹结构:
program.cs 的内容:
using microsoft.codeanalysis; using microsoft.codeanalysis.csharp; using microsoft.codeanalysis.csharp.syntax; using system; using system.collections.generic; using system.io; using system.linq; using system.reflection; using system.runtime.loader; using system.threading; namespace common { public interface iplugin : idisposable { string getmessage(); } } namespace host { using common; internal class plugincontroller : iplugin { private list<assembly> _defaultassemblies; private assemblyloadcontext _context; private string _pluginname; private string _plugindirectory; private volatile iplugin _instance; private volatile bool _changed; private object _reloadlock; private filesystemwatcher _watcher; public plugincontroller(string pluginname, string plugindirectory) { _defaultassemblies = assemblyloadcontext.default.assemblies .where(assembly => !assembly.isdynamic) .tolist(); _pluginname = pluginname; _plugindirectory = plugindirectory; _reloadlock = new object(); listenfilechanges(); } private void listenfilechanges() { action<string> onfilechanged = path => { if (path.getextension(path).tolower() == ".cs") _changed = true; }; _watcher = new filesystemwatcher(); _watcher.path = _plugindirectory; _watcher.includesubdirectories = true; _watcher.notifyfilter = notifyfilters.lastwrite | notifyfilters.filename; _watcher.changed += (sender, e) => onfilechanged(e.fullpath); _watcher.created += (sender, e) => onfilechanged(e.fullpath); _watcher.deleted += (sender, e) => onfilechanged(e.fullpath); _watcher.renamed += (sender, e) => { onfilechanged(e.fullpath); onfilechanged(e.oldfullpath); }; _watcher.enableraisingevents = true; } private void unloadplugin() { _instance?.dispose(); _instance = null; _context?.unload(); _context = null; } private assembly compileplugin() { var bindirectory = path.combine(_plugindirectory, "bin"); var dllpath = path.combine(bindirectory, $"{_pluginname}.dll"); if (!directory.exists(bindirectory)) directory.createdirectory(bindirectory); if (file.exists(dllpath)) { file.delete($"{dllpath}.old"); file.move(dllpath, $"{dllpath}.old"); } var sourcefiles = directory.enumeratefiles( _plugindirectory, "*.cs", searchoption.alldirectories); var compilationoptions = new csharpcompilationoptions( outputkind.dynamicallylinkedlibrary, optimizationlevel: optimizationlevel.debug); var references = _defaultassemblies .select(assembly => assembly.location) .where(path => !string.isnullorempty(path) && file.exists(path)) .select(path => metadatareference.createfromfile(path)) .tolist(); var syntaxtrees = sourcefiles .select(p => csharpsyntaxtree.parsetext(file.readalltext(p))) .tolist(); var compilation = csharpcompilation.create(_pluginname) .withoptions(compilationoptions) .addreferences(references) .addsyntaxtrees(syntaxtrees); var emitresult = compilation.emit(dllpath); if (!emitresult.success) { throw new invalidoperationexception(string.join("\r\n", emitresult.diagnostics.where(d => d.warninglevel == 0))); } //return _context.loadfromassemblypath(path.getfullpath(dllpath)); using (var stream = file.openread(dllpath)) { var assembly = _context.loadfromstream(stream); return assembly; } } private iplugin getinstance() { var instance = _instance; if (instance != null && !_changed) return instance; lock (_reloadlock) { instance = _instance; if (instance != null && !_changed) return instance; unloadplugin(); _context = new assemblyloadcontext( name: $"plugin-{_pluginname}", iscollectible: true); var assembly = compileplugin(); var plugintype = assembly.gettypes() .first(t => typeof(iplugin).isassignablefrom(t)); instance = (iplugin)activator.createinstance(plugintype); _instance = instance; _changed = false; } return instance; } public string getmessage() { return getinstance().getmessage(); } public void dispose() { unloadplugin(); _watcher?.dispose(); _watcher = null; } } internal class program { static void main(string[] args) { using (var controller = new plugincontroller("myplugin", "../guest")) { bool keeprunning = true; console.cancelkeypress += (sender, e) => { e.cancel = true; keeprunning = false; }; while (keeprunning) { try { console.writeline(controller.getmessage()); } catch (exception ex) { console.writeline($"{ex.gettype()}: {ex.message}"); } thread.sleep(1000); } } } } }
host.csproj 的内容:
<project sdk="microsoft.net.sdk"> <propertygroup> <outputtype>exe</outputtype> <targetframework>netcoreapp3.0</targetframework> </propertygroup> <itemgroup> <packagereference include="microsoft.codeanalysis.csharp" version="3.3.1" /> </itemgroup> </project>
plugin.cs 的内容:
using system; using common; namespace guest { public class myplugin : iplugin { public myplugin() { console.writeline("myplugin loaded"); } public string getmessage() { return "hello 1"; } public void dispose() { console.writeline("myplugin unloaded"); } } }
进入 pluginexample/host
下运行 dotnet run
即可启动宿主程序,这时宿主程序会自动编译与加载插件,检测插件文件的变化并在变化时重新编译加载。你可以在运行后修改 pluginexample/guest/plugin.cs
中的 hello 1
为 hello 2
,之后可以看到类似以下的输出:
myplugin loaded hello 1 hello 1 hello 1 myplugin unloaded myplugin loaded hello 2 hello 2
我们可以看到程序自动更新并执行修改以后的代码,如果你有兴趣还可以测试插件代码语法错误时会出现什么。
接下来是对宿主的源代码中各个部分的详细讲解:
public interface iplugin : idisposable { string getmessage(); }
这是插件项目需要的实现接口,宿主项目在编译插件后会寻找程序集中实现 iplugin 的类型,创建这个类型的实例并且使用它,创建插件时会调用构造函数,卸载插件时会调用 dispose 方法。如果你用过 .net framework 的 appdomain 机制可能会想是否需要 marshalling 处理,答案是不需要,.net core 的可回收程序集会加载到当前的 appdomain 中,回收时需要依赖 gc 清理,好处是使用简单并且运行效率高,坏处是 gc 清理有延迟,只要有一个插件中类型的实例没有被回收则插件程序集使用的数据会一直残留,导致内存泄漏。
internal class plugincontroller : iplugin { private list<assembly> _defaultassemblies; private assemblyloadcontext _context; private string _pluginname; private string _plugindirectory; private volatile iplugin _instance; private volatile bool _changed; private object _reloadlock; private filesystemwatcher _watcher;
这是管理插件的代理类,在内部它负责编译与加载插件,并且把对 iplugin 接口的方法调用转发到插件的实现中。类成员包括默认 assemblyloadcontext 中的程序集列表 _defaultassemblies
,用于加载插件的自定义 assemblyloadcontext _context
,插件名称与文件夹,插件实现 _instance
,标记插件文件是否已改变的 _changed
,防止多个线程同时编译加载插件的 _reloadlock
,与监测插件文件变化的 _watcher
。
public plugincontroller(string pluginname, string plugindirectory) { _defaultassemblies = assemblyloadcontext.default.assemblies .where(assembly => !assembly.isdynamic) .tolist(); _pluginname = pluginname; _plugindirectory = plugindirectory; _reloadlock = new object(); listenfilechanges(); }
构造函数会从 assemblyloadcontext.default.assemblies
中获取默认 assemblyloadcontext 中的程序集列表,包括宿主程序集、system.runtime 等,这个列表会在 roslyn 编译插件时使用,表示插件编译时需要引用哪些程序集。之后还会调用 listenfilechanges
监听插件文件是否有改变。
private void listenfilechanges() { action<string> onfilechanged = path => { if (path.getextension(path).tolower() == ".cs") _changed = true; }; _watcher = new filesystemwatcher(); _watcher.path = _plugindirectory; _watcher.includesubdirectories = true; _watcher.notifyfilter = notifyfilters.lastwrite | notifyfilters.filename; _watcher.changed += (sender, e) => onfilechanged(e.fullpath); _watcher.created += (sender, e) => onfilechanged(e.fullpath); _watcher.deleted += (sender, e) => onfilechanged(e.fullpath); _watcher.renamed += (sender, e) => { onfilechanged(e.fullpath); onfilechanged(e.oldfullpath); }; _watcher.enableraisingevents = true; }
这个方法创建了 filesystemwatcher
,监听插件文件夹下的文件是否有改变,如果有改变并且改变的是 c# 源代码 (.cs 扩展名) 则设置 _changed
成员为 true,这个成员标记插件文件已改变,下次访问插件实例的时候会触发重新加载。
你可能会有疑问,为什么不在文件改变后立刻触发重新加载插件,一个原因是部分文件编辑器的保存文件实现可能会导致改变的事件连续触发几次,延迟触发可以避免编译多次,另一个原因是编译过程中出现的异常可以传递到访问插件实例的线程中,方便除错与调试 (尽管使用 exceptiondispatchinfo 也可以做到)。
private void unloadplugin() { _instance?.dispose(); _instance = null; _context?.unload(); _context = null; }
这个方法会卸载已加载的插件,首先调用 iplugin.dispose
通知插件正在卸载,如果插件创建了新的线程可以在 dispose
方法中停止线程避免泄漏,然后调用 assemblyloadcontext.unload
允许 .net core 运行时卸载这个上下文加载的程序集,程序集的数据会在 gc 检测到所有类型的实例都被回收后回收 (参考文章开头的链接)。
private assembly compileplugin() { var bindirectory = path.combine(_plugindirectory, "bin"); var dllpath = path.combine(bindirectory, $"{_pluginname}.dll"); if (!directory.exists(bindirectory)) directory.createdirectory(bindirectory); if (file.exists(dllpath)) { file.delete($"{dllpath}.old"); file.move(dllpath, $"{dllpath}.old"); } var sourcefiles = directory.enumeratefiles( _plugindirectory, "*.cs", searchoption.alldirectories); var compilationoptions = new csharpcompilationoptions( outputkind.dynamicallylinkedlibrary, optimizationlevel: optimizationlevel.debug); var references = _defaultassemblies .select(assembly => assembly.location) .where(path => !string.isnullorempty(path) && file.exists(path)) .select(path => metadatareference.createfromfile(path)) .tolist(); var syntaxtrees = sourcefiles .select(p => csharpsyntaxtree.parsetext(file.readalltext(p))) .tolist(); var compilation = csharpcompilation.create(_pluginname) .withoptions(compilationoptions) .addreferences(references) .addsyntaxtrees(syntaxtrees); var emitresult = compilation.emit(dllpath); if (!emitresult.success) { throw new invalidoperationexception(string.join("\r\n", emitresult.diagnostics.where(d => d.warninglevel == 0))); } //return _context.loadfromassemblypath(path.getfullpath(dllpath)); using (var stream = file.openread(dllpath)) { var assembly = _context.loadfromstream(stream); return assembly; } }
这个方法会调用 roslyn 编译插件代码到 dll,并使用自定义的 assemblyloadcontext 加载编译后的 dll。首先它需要删除原有的 dll 文件,因为卸载程序集有延迟,原有的 dll 文件在 windows 系统上很可能会删除失败并提示正在使用,所以需要先重命名并在下次删除。接下来它会查找插件文件夹下的所有 c# 源代码,用 csharpsyntaxtree
解析它们,并用 csharpcompilation
编译,编译时引用的程序集列表是构造函数中取得的默认 assemblyloadcontext 中的程序集列表 (包括宿主程序集,这样插件代码才可以使用 iplugin 接口)。编译成功后会使用自定义的 assemblyloadcontext 加载编译后的 dll 以支持卸载。
这段代码中有两个需要注意的部分,第一个部分是 roslyn 编译失败时不会抛出异常,编译后需要判断 emitresult.success
并从 emitresult.diagnostics
找到错误信息;第二个部分是加载插件程序集必须使用 assemblyloadcontext.loadfromstream
从内存数据加载,如果使用 assemblyloadcontext.loadfromassemblypath
那么下次从同一个路径加载时仍然会返回第一次加载的程序集,这可能是 .net core 3.0 的实现问题并且有可能在以后的版本修复。
private iplugin getinstance() { var instance = _instance; if (instance != null && !_changed) return instance; lock (_reloadlock) { instance = _instance; if (instance != null && !_changed) return instance; unloadplugin(); _context = new assemblyloadcontext( name: $"plugin-{_pluginname}", iscollectible: true); var assembly = compileplugin(); var plugintype = assembly.gettypes() .first(t => typeof(iplugin).isassignablefrom(t)); instance = (iplugin)activator.createinstance(plugintype); _instance = instance; _changed = false; } return instance; }
这个方法是获取最新插件实例的方法,如果插件实例已创建并且文件没有改变,则返回已有的实例,否则卸载原有的插件、重新编译插件、加载并生成实例。注意 assemblyloadcontext 类型在 netstandard (包括 2.1) 中是 abstract 类型,不能直接创建,只有 netcoreapp3.0 才可以直接创建 (目前也只有 .net core 3.0 支持这项机制),如果需要支持可回收则创建时需要设置 iscollectible 参数为 true,因为支持可回收会让 gc 扫描对象时做一些额外的工作所以默认不启用。
public string getmessage() { return getinstance().getmessage(); }
这个方法是代理方法,会获取最新的插件实例并转发调用参数与结果,如果 iplugin 有其他方法也可以像这个方法一样写。
public void dispose() { unloadplugin(); _watcher?.dispose(); _watcher = null; }
这个方法支持主动释放 plugincontroller,会卸载已加载的插件并且停止监听插件文件。因为 plugincontroller 没有直接管理非托管资源,并且 assemblyloadcontext 的析构函数 会触发卸载,所以 plugincontroller 不需要提供析构函数。
static void main(string[] args) { using (var controller = new plugincontroller("myplugin", "../guest")) { bool keeprunning = true; console.cancelkeypress += (sender, e) => { e.cancel = true; keeprunning = false; }; while (keeprunning) { try { console.writeline(controller.getmessage()); } catch (exception ex) { console.writeline($"{ex.gettype()}: {ex.message}"); } thread.sleep(1000); } } }
主函数创建了 plugincontroller 实例并指定了上述的 guest 文件夹为插件文件夹,之后每隔 1 秒调用一次 getmessage 方法,这样插件代码改变的时候我们可以从控制台输出中观察的到,如果插件代码包含语法错误则调用时会抛出异常,程序会继续运行并在下一次调用时重新尝试编译与加载。
本文的介绍就到此为止了,在本文中我们看到了一个最简单的 .net core 3.0 插件热加载实现,这个实现仍然有很多需要改进的地方,例如如何管理多个插件、怎么在重启宿主程序后避免重新编译所有插件,编译的插件代码如何调试等,如果你有兴趣可以解决它们,做一个插件系统嵌入到你的项目中,或者写一个新的框架。
关于 zkweb,3.0 会使用了本文介绍的机制实现插件热加载,但因为我目前已经退出 it 行业,所有开发都是业余空闲时间做的,所以基本上不会有很大的更新,zkweb 更多的会作为一个框架的实现参考。此外,我正在使用 c++ 编写 http 框架 ,主要着重性能 (吞吐量是 .net core 3.0 的两倍以上,与 actix-web 持平),目前还没有正式发布。
关于书籍,出版社约定 11 月但目前还没有让我看修改过的稿件 (尽管我问的时候会回答),所以很大可能会继续延期,抱歉让期待出版的同学们久等了,书籍目前还是基于 .net core 2.2 而不是 .net core 3.0。
如对本文有疑问, 点击进行留言回复!!
Asp.Net Core 3.1 Web Api 返回数据字段被转换为小驼峰格式的解决办法
已知两点经纬度,计算偏移角(正北为0,顺时针为正,逆时针为负)
解决问题“Could not load file or assembly xxxxxxx or one of its dependencies”
网友评论