[英]Will holding a reference to a string-property of an Entity Framework object keep it from being collected by the GC?
我使用實體框架從MySQL數據庫加載條目,並創建一個新對象,然后將字符串屬性從數據庫對象發送到構造函數中並返回新對象(不直接引用任何數據庫類)。
當我運行內存分析器時,我看到這些數據庫實體的負載保存在內存中。 這是正確的還是有什么辦法可以解決這個問題?
var eoList = new List<EnterpriseObject>();
using(var context = new DatabaseContext())
{
var infos = context.tableName.Where(dbObject => dbObject.Date > DateTime.UtcNow).ToList();
foreach (var dbObject in infos)
{
IEnumerable<SomeEnum> enums = dbObject.enumStrings.Select(enumString => enumString.ToSomeEnum()); // Added in edited, as this was the problem, this IEnumerable was a property in the EnterpriseObject and somehow kept references to the DbObjects. Changing the property to a List<SomeEnum> fixed my problem.
var entepriseObject = new EnterpriseObject(dbObject.Name, dbObject.Date, enums);
eoList.Add(enterpiseObject);
}
}
return eoList;
只要引用了“ eoList”對象,上面的代碼是否會將所有引用實際上保留在“信息”中?
如果是這樣,是否有更好的方法來避免此問題?
托馬斯
編輯:對於其他人正在尋找此問題,請檢查我添加的代碼行,這就是問題。
假設.Name
和.Date
返回令人驚訝的類型1 ,那么否,您的EnterpriseObject
不知道這些值來自dbObject
並且(本身)不負責使它們保持活動狀態。
我希望一個好的內存探查器可以告訴您對象是如何生根的 ,即“是什么使該對象保持活動狀態?”。 如果沒有,則可以進行內存轉儲並使用WinDbg / SOS回答相同的問題。 不要猜測根源可能是什么。
在WinDBg
, SOS
和gcroot
上WinDBg
搜索可能會為您帶來一些結果,盡管大約10年左右沒有人寫任何新文章。 還有一個VisualSOS.Extension
for Visual Studio看起來不錯,但我自己還沒有嘗試過。
1也就是說,發現Date
返回this
並且該類型還支持從其自身到DateTime
的隱式轉換,以便Where
lambda進行編譯是很令人驚訝的:-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.