1

I don't understand why in this situation context is not unload

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();
    }

But now context context is successfully unloaded.

    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");
    }

Why? and how i can fix unload in first example?

fuz
  • 88,405
  • 25
  • 200
  • 352
Pavel
  • 11
  • 1

1 Answers1

1

It looks to me like your assembly variable is holding a reference to your loaded DLL.

It works in the second example because you've declared assembly as a local variable of a method, so the variable goes out of scope when control flow leaves the method.

There are other caveats. See here.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • Yes. I think too. And problem was in "Debug". -> Details [here](http://stackoverflow.com/a/17131389/17034) – Pavel Sep 06 '20 at 20:20