【发布时间】:2013-12-04 14:21:17
【问题描述】:
我正在开发一个类库。
一个实用方法被频繁调用,并被传递给一个复杂的第三方对象。 该方法使用来自模型的数据,这些数据收集起来很耗时。 因此,出于性能原因,我想将数据缓存到 Dictionary 类中,以便一次性收集必要的数据,然后将其用于所有连续调用。
但是,出于多种原因,要求库的使用者维护一个可以存储字典的对象实例并不方便。
是否可以创建一个可以像静态字段一样访问的对象,但如果收集到另一个(指定的)对象,则该对象会被收集?
准码:
SomeMethodRequiringALotOfDataFromHugeSystem(detector detectorInHugeSystem)
{
//access HugeSystem from a property in the dectector.
//find if Huge System already has a Dictioary.
//Build a Dictionary from data in Huge system if necessary.
//(Not possible?) Associate the dictionary to the HugeSystem object instance so that Dictionary will be collected if HugeSystem instance is collected.
// Perform time efficient task based on Dictionary.
}
【问题讨论】:
-
在什么情况下会收集到探测器对象?
-
坏主意,不要这样做。您需要一个计时器来定期检查客户端对象是否尚未被收集。你用 WeakReference.IsAlive 做什么。
-
我正在通过探测器到达“巨大的系统”。该方法需要这些数据才能为检测器提供服务。但是,由于构建成本高昂,我想在处理同一个“庞大系统”中的各种检测器时在连续调用中重用缓存。
标签: .net c#-4.0 memory garbage-collection