我創建了一個使用相對較新的 AssemblyLoadContext 物件的測驗應用程式。我現在的問題是,盡管我做了我能在檔案中找到的一切。它不卸載。沒有太多出錯的余地,因為我所做的只是加載然后嘗試卸載。
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();
}
}
uj5u.com熱心網友回復:
我認為您的代碼存在一些問題:
alc永遠不會超出范圍,因此垃圾收集器不太可能收集它。根據 Pro .NET 記憶體管理,在除錯模式下,在方法結束之前不會收集區域變數。這與超出范圍的檔案示例不同。AssemblyLoadContext- 您正在加載程式集
AssemblyLoadContext.Default,而不是alc. 這是故意的嗎?
如果您正在尋找有關 的更多檔案AssemblyLoadContext,C# 9.0 In A Nutshell 一書詳細介紹了它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/437616.html
