ln.objects/ng/IdentityCache.cs

57 lines
1.5 KiB
C#

using System;
using ln.types.collections;
namespace ln.types.odb.ng
{
public class IdentityCache
{
WeakKeyReferenceDictionary<object, Guid> reverseCache = new WeakKeyReferenceDictionary<object, Guid>();
WeakValueDictionary<Guid, object> forwardCache = new WeakValueDictionary<Guid, object>();
public IdentityCache()
{
}
public bool TryGetValue(Guid identity,out object o)
{
lock (this)
{
return forwardCache.TryGetValue(identity, out o);
}
}
public bool TryGetValue(Guid identity, out object o, Func<object> instantiator)
{
lock (this)
{
if (!TryGetValue(identity, out o))
{
o = instantiator();
forwardCache.Add(identity, o);
reverseCache.Add(o, identity);
}
return false;
}
}
public bool TryGetIdentity(object o,out Guid identity)
{
lock (this)
{
return reverseCache.TryGetValue(o, out identity);
}
}
public void Ensure(Guid identity,object o)
{
lock (this)
{
if (!forwardCache.ContainsKey(identity))
forwardCache.Add(identity, o);
if (!reverseCache.ContainsKey(o))
reverseCache.Add(o, identity);
}
}
}
}