如果可行,我将如何管理这个池?我如何确定某个区域是否不再需要任何任务并且可以安全地丢弃?
一个简单的方法是使用弱引用:
public class RegionStore
{
// I'm using int as the identifier for a region.
// Obviously this must be some type that can serve as
// an ID according to your application's logic.
private Dictionary<int, WeakReference<Region>> _store = new Dictionary<int, WeakReference<Region>>();
private const int TrimThreshold = 1000; // Profile to find good value here.
private int _addCount = 0;
public bool TryGetRegion(int id, out Region region)
{
WeakReference<Region> wr;
if(!_store.TryGetValue(id, out wr))
return false;
if(wr.TryGetTarget(out region))
return true;
// Clean up space in dictionary.
_store.Remove(id);
return false;
}
public void AddRegion(int id, Region region)
{
if(++_addCount >= TrimThreshold)
Trim();
_store[id] = new WeakReference<Region>(region);
}
public void Remove(int id)
{
_store.Remove(id);
}
private void Trim()
{
// Remove dead keys.
// Profile to test if this is really necessary.
// If you were fully implementing this, rather than delegating to Dictionary,
// you'd likely see if this helped prior to an internal resize.
_addCount = 0;
var keys = _store.Keys.ToList();
Region region;
foreach(int key in keys)
if(!_store[key].TryGetTarget(out wr))
_store.Remove(key);
}
}
现在您有了Region
对象的存储,但如果不存在对它们的其他引用,该存储不会阻止它们被垃圾收集。
某些任务将是修改区域。在这种情况下,我可能会在区域对象中引发“更新”标志,并从那里更新使用它的所有其他任务。
请注意,这将是整个应用程序中潜在的错误来源。可变性使任何类型的缓存变得复杂。如果您可以迁移到不可变模型,它可能会简化事情,但是使用过时的对象会带来其自身的复杂性。