【问题标题】:If I use the property of an object as the key in Memory Cache, will that object still be garbage collected?如果我使用对象的属性作为内存缓存中的键,该对象是否仍会被垃圾回收?
【发布时间】:2021-08-25 22:54:40
【问题描述】:

假设您有一个像 User 这样的对象,其中一个属性是 UserName。假设您想使用 C# MemoryCache 来存储有关该用户的一些信息,并使用 UserName 字符串属性作为缓存中的键。

这会阻止用户对象的垃圾收集吗?

【问题讨论】:

  • 我们需要minimal reproducible example。简短的回答 - 如果UserMemoryCache 中的键或值,它将阻止垃圾收集。如果没有,它不会。

标签: c# .net caching garbage-collection memorycache


【解决方案1】:

如果我理解正确,您保存的是属性值(在这种情况下为字符串)而不是对象本身,因此您的对象将被垃圾回收。

【讨论】:

  • In this case it should be copied by value and not by reference 这个陈述要么是错误的,要么是多余的。最好删除它。
猜你喜欢
  • 1970-01-01
  • 2012-01-31
  • 1970-01-01
  • 1970-01-01
  • 2014-03-18
  • 1970-01-01
  • 1970-01-01
  • 2019-03-09
  • 1970-01-01
相关资源
最近更新 更多