First time posting here, hope you guys can help me out.
I'm creating an application that can load and unload assemblies without having to restart the application.
Loading and unloading of an assembly works without issues the first time, but when loading and unloading a dll that has already been unloaded before i get an application crash. Sometimes the dll will load/unload a couple of times before the application crashes, but it always crashes on the same line (GC.WaitForPendingFinalizers();).
I'm using .net core 3 preview 6 in visual studio prof 2019 version 16.1.3.
Am I doing something wrong or is this possibly a bug in .net core?
See below for sample code that has the issue.
using System;
using System.Reflection;
using System.Runtime.Loader;
namespace ConsoleApp1 {
class Program {
static void Main() {
try {
for (int index = 0; index < 99; index++) {
WeakReference weakReference = Load(@"C:\TestAssembly.dll"); ;
for (var i = 0; i < 8 && weakReference.IsAlive; i++) {
GC.Collect();
Console.WriteLine($"\tGC.Collect done!");
GC.WaitForPendingFinalizers();
Console.WriteLine($"\tGC.WaitForPendingFinalizers done!");
}
Console.WriteLine(Environment.NewLine + $"Unloading assembly: {(!weakReference.IsAlive ? "success" : "failed")}!");
}
} catch (Exception exception) {
Console.WriteLine(exception.Message);
}
}
public class CollectibleAssemblyLoadContext : AssemblyLoadContext {
public CollectibleAssemblyLoadContext() : base(isCollectible: true) { }
}
private static WeakReference Load(string assemblyPath) {
CollectibleAssemblyLoadContext context = new CollectibleAssemblyLoadContext();
Assembly assembly = context.LoadFromAssemblyPath(assemblyPath);
// Do something with loaded assembly
// .......
context.Unload();
Console.WriteLine($"Unloading assembly");
return new WeakReference(context);
}
}
}
using System;
namespace TestAssembly {
public class Class1 {
}
}
Output:
Unloading assembly
GC.Collect done!
GC.WaitForPendingFinalizers done!
GC.Collect done!
GC.WaitForPendingFinalizers done!
Unloading assembly: success!
Unloading assembly
GC.Collect done!
Followed by a program crash: HRESULT=0x80070057. ErrorCode=0x0.
Aucun commentaire:
Enregistrer un commentaire