AssemblyLoadContext 不会卸载

AssemblyLoadContext Will Not Unload

我创建了一个测试应用程序,它使用了相对较新的 AssemblyLoadContext 对象。我现在的问题是,尽管我做了我能在文档中找到的一切。它不卸载。没有那么多错误的余地,因为我所做的只是加载然后尝试卸载。

private void FileWatcher_OnServerPluginLoaded(object sender, string e)
{
    AssemblyLoadContext alc = new AssemblyLoadContext("meme", true);

    WeakReference testAlcWeakRef = new WeakReference(alc);

    Assembly assembly = null;

    using (var fs = File.Open(e, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        assembly = alc.Default.LoadFromStream(fs);
    }

    assembly = null;

    alc.Unload();

    GC.Collect();

    while (testAlcWeakRef.IsAlive)
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

我认为您的代码存在一些问题:

  1. alc 永远不会超出范围,因此垃圾收集器不太可能收集它。根据 Pro .NET 内存管理,在调试模式下,局部变量不会在方法结束前被收集。这与 the docs example 不同,其中 AssemblyLoadContext 超出范围。
  2. 您正在使用 AssemblyLoadContext.Default 而不是 alc 加载程序集。是故意的吗?

如果您要查找有关 AssemblyLoadContext 的更多文档,《C# 9.0 简述》一书对此进行了详细介绍。