这是来自微软文档的代码。请注意代码中的注释
class TestAssemblyLoadContext : AssemblyLoadContext
{
private AssemblyDependencyResolver _resolver;
public TestAssemblyLoadContext(string mainAssemblyToLoadPath) : base(isCollectible: true)
{
_resolver = new AssemblyDependencyResolver(mainAssemblyToLoadPath);
}
protected override Assembly Load(AssemblyName name)
{
string assemblyPath = _resolver.ResolveAssemblyToPath(name);
if (assemblyPath != null)
{
return LoadFromAssemblyPath(assemblyPath);
}
return null;
}
}
这是插件接口代码
public interface IPlugin
{
string result { get; }
}
这是加载和卸载方法(我从microsoft doc修改了代码)
private static string pluginPath = @"C:\PluginFolder\MyPlugin.dll"; //interface is IPlugin
private static TestAssemblyLoadContext talc; //the assemblyloadcontext
[MethodImpl(MethodImplOptions.NoInlining)]
static void LoadIt(string assemblyPath)
{
talc = new PluginFactory.TestAssemblyLoadContext(pluginPath); //create instance
Assembly a = talc.LoadFromAssemblyPath(assemblyPath);
//assemblyPath cant delete now because is loaded
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void UnloadIt()
{
talc.Unload();
for (int i = 0; i < 10; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
//if success unload, file on assemblyPath can success delete.
File.Delete(assemblyPath);
}
这是 wpf 程序代码的一部分
public MainWindow()
{
InitializeComponent();
LoadIt(pluginPath); //loaded assembly
UnloadIt(pluginPath); //success unload assembly, file assembly can delete.
}
private static TestAssemblyLoadContext talc;
LoadIt(){...}
UnloadIt(){...}
如果卸货码和装货码不在一起
public MainWindow()
{
InitializeComponent();
LoadIt(pluginPath); //loaded assembly
}
private void Button_Click(object sender, RoutedEventArgs e)
{
UnloadIt(pluginPath); //unsuccessful. File assembly cant delete.
}
private static TestAssemblyLoadContext talc;
LoadIt(){...}
UnloadIt(){...}
但是,如果在 Wpf 初始化函数“MainWindow()”或 wpf 应用程序事件(例如 Loaded 事件、ContentRendered 事件、Activated 事件)中没有调用加载代码,它将起作用。
public MainWindow()
{
InitializeComponent();
}
private void LoadButton_Click(object sender, RoutedEventArgs e)
{
LoadIt(pluginPath); //load plugin with button click event.
}
private void UnloadButton_Click(object sender, RoutedEventArgs e)
{
UnloadIt(pluginPath) //It successful unload, assembly file can be deleted.
}
private static TestAssemblyLoadContext talc;
LoadIt(){...}
UnloadIt(){...}
谁能告诉我为什么?这可能是一个错误吗?
您可以将代码复制到新的 wpf 程序中进行测试。我的运行时框架是.Net 5。