【问题标题】:.net core 3. Unload assemblies.net core 3.卸载程序集
【发布时间】:2020-09-06 18:13:01
【问题描述】:

我不明白为什么在这种情况下上下文没有卸载

class Program
{
    static void Main(string[] args)
    {
        CustomAssemblyLoadContext context = new CustomAssemblyLoadContext();
        Assembly assembly = context.LoadFromAssemblyPath(@"C:\Users\Greedy\source\repos\ConsoleApp1\MyApp\bin\Debug\netcoreapp3.1\MyApp.dll");
        context.Unload();
        
        GC.Collect();
        GC.WaitForPendingFinalizers();

        foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
            Console.WriteLine(asm.GetName().Name);

        Console.Read();
    }

但现在上下文上下文已成功卸载。

    class Program
{
    static void Main(string[] args)
    {
        CustomAssemblyLoadContext context = new CustomAssemblyLoadContext();
        Load(context);
        context.Unload();
        
        GC.Collect();
        GC.WaitForPendingFinalizers();

        foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
            Console.WriteLine(asm.GetName().Name);

        Console.Read();
    }

    static void Load(CustomAssemblyLoadContext context)
    {
        Assembly assembly = context.LoadFromAssemblyPath(@"C:\Users\Greedy\source\repos\ConsoleApp1\MyApp\bin\Debug\netcoreapp3.1\MyApp.dll");
    }

为什么?以及如何在第一个示例中修复卸载?

【问题讨论】:

标签: c# .net .net-assembly


【解决方案1】:

在我看来,您的 assembly 变量包含对您加载的 DLL 的引用。

它在第二个示例中有效,因为您已将 assembly 声明为方法的局部变量,因此当控制流离开方法时该变量超出范围。

还有其他注意事项。见here

【讨论】:

  • 是的。我也这么想。问题出在“调试”中。 -> 详情here
猜你喜欢
  • 2014-07-08
  • 2023-04-03
  • 1970-01-01
  • 2017-04-15
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
  • 2018-06-28
  • 1970-01-01
相关资源
最近更新 更多