当前位置: 移动技术网 > IT编程>开发语言>.net > .NET Core 3.0 可回收程序集加载上下文的实现

.NET Core 3.0 可回收程序集加载上下文的实现

2019年07月18日  | 移动技术网IT编程  | 我要评论

wi7系统下载,不良百货公司物语,高考满分是多少分

一、前世今生

.net诞生以来,程序集的动态加载和卸载都是一个hack的技术,之前的netfx都是使用appdomain的方式去加载程序集,然而appdomain并没有提供直接卸载一个程序集的api,而是要卸载整个appdomain才能卸载包含在其中的所有程序集。然而卸载整个currentappdomain会使程序不能工作。可能有人另辟西经,创建别一个appdomain来加载/卸载程序集,但是由于程序集之间是不能跨域访问的,也导致只能通过remote proxy的方式去访问,这样在类型创建和使用上带来了一定的难度也是类型的继承变得相当复杂。

.net core中一直没有appdomain的支持。但是在.net core 3.0中,我最期待的一个特性就是对可收集程序集的支持(collectible assemblyloadcontext)。 众所周知.net core中一直使用assemblyloadcontext的api,来进行程序集的动态加载,但是并没有提供unload的方法,此次升级更新了这方面的能力。

二、assemblyloadcontext

其实这次assemblyloadcontext的设计,我认为更像是java中classloader的翻版,可以说非常类似。在使用过程中自定义assemblyloadcontext可以内部管理其中的程序集,并对整体context进行unload。使用assemblyloadcontext也可以避免程序集名称和版本的冲突。

三、getting started

.net core 3.0还没有正式版,所有要使用预览版的sdk完成以下实例。我使用的是.net core sdk 3.0.100-preview-009812

dotnet new globaljson --sdk-version 3.0.100-preview-009812

assemblyloadcontext是一个抽象类的,我们需要子类化。下面显示的是我们创建自定义assemblyloadcontext的方法,实现一个可回收的context需要在构造器中指定iscollectible: true :

public class collectibleassemblyloadcontext : assemblyloadcontext
{
  public collectibleassemblyloadcontext() : base(iscollectible: true)
  { }
 
  protected override assembly load(assemblyname assemblyname)
  {
    return null;
  }
}

使用netstandard2.0创建一个library

using system;
 
namespace samplelibrary
{
  public class sayhello
  {
    public void hello(int iteration)
    {
      console.writeline($"hello {iteration}!");
    }
  }
}

测试load/unload

var context = new collectibleassemblyloadcontext();
var assemblypath = path.combine(directory.getcurrentdirectory(),"samplelibrary.dll");
using (var fs = new filestream(assemblypath, filemode.open, fileaccess.read))
{
  var assembly = context.loadfromstream(fs);

  var type = assembly.gettype("samplelibrary.sayhello");
  var greetmethod = type.getmethod("hello");

  var instance = activator.createinstance(type);
  greetmethod.invoke(instance, new object[] { i });
}

context.unload();

gc.collect();
gc.waitforpendingfinalizers();

当执行gc收回后,加载的程序集会被完全的回收。

四、最后

github:https://github.com/maxzhang1985/yoyofx 如果觉还可以请star下, 欢迎一起交流。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网