首页 > 解决方案 > 无法在 .NET Core 3 中卸载 DLL

问题描述

我正在尝试卸载外部程序集,但它仍在内存中,我无法删除 dll 文件。这是我的代码 - 我做错了什么?

上传的 dll 非常简单——只有 1 个类和一种方法。没有依赖关系。

我查看了许多示例,发现代码中没有问题,但它仍然无法正常工作。

谢谢 !

class SimpleUnloadableAssemblyLoadContext : AssemblyLoadContext
{
    public SimpleUnloadableAssemblyLoadContext( ) : base(isCollectible: true)
    {
    }
    protected override Assembly Load(AssemblyName name)
    {
        return null;
    }
}

public class PluginLoader2
{

    [MethodImpl(MethodImplOptions.NoInlining)]
    public string getExternalText()
    {
        string res = "";
        var sourcesPath = Path.Combine(Environment.CurrentDirectory, "Plugins");

        string[] fileEntries = Directory.GetFiles(sourcesPath);
        foreach (string fileName in fileEntries)
        {
            SimpleUnloadableAssemblyLoadContext context = new SimpleUnloadableAssemblyLoadContext();
            WeakReference w_r = new WeakReference(context, trackResurrection: true);

            var myAssembly = context.LoadFromAssemblyPath(fileName);

            context.Unload();
            for (var i = 0; i < 10 && w_r.IsAlive; i++)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            res += "<br /><br />" + fileName + " live status is " + w_r.IsAlive.ToString();
        }

        return res;
    }
}

标签: dll.net-core.net-assembly

解决方案


推荐阅读