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();
}
}
CodePudding user response:
I think there are a few issues with your code:
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 theAssemblyLoadContext
goes out of scope.- You're loading the assembly with
AssemblyLoadContext.Default
, notalc
. Is that intentional?
If you're looking for more documentation on AssemblyLoadContext
, the book C# 9.0 In A Nutshell covers it in detail.