Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AssemblyLoadContext Will Not Unload

Tags:

c#

.net

.net-core

I have created a test application that utilizes the relatively new AssemblyLoadContext object. My issue now is that despite me doing everything I could find in the documentation. It does not unload. There isn't that much room for error, as all I am doing is loading then trying to unload.

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();
    }
}
like image 483
Meme Machine Avatar asked Sep 01 '25 16:09

Meme Machine


1 Answers

I think there are a few issues with your code:

  1. alc never goes out of scope, so the the garbage collector is less likely to collect it. According to Pro .NET Memory Management, in Debug mode local variables will not be collected before the end of a method. This is different from the docs example in which the AssemblyLoadContext goes out of scope.
  2. You're loading the assembly with AssemblyLoadContext.Default, not alc. Is that intentional?

If you're looking for more documentation on AssemblyLoadContext, the book C# 9.0 In A Nutshell covers it in detail.

like image 174
Reilly Wood Avatar answered Sep 04 '25 05:09

Reilly Wood