.NET and Java supports weak references with the aptly named WeakReference class. In .NET it exposes a .Target property of type object that weakly points to whatever you like.
Java also sports a generic WeakReference
Here is my attempt at a WeakReference
using System;
using System.Runtime.InteropServices;
public class WeakReference
{
private GCHandle handle;
private bool trackResurrection;
public WeakReference(T target)
: this(target, false)
{
}
public WeakReference(T target, bool trackResurrection) {
this.trackResurrection = trackResurrection;
this.Target = target;
}
~WeakReference() {
Dispose();
}
public void Dispose() {
handle.Free();
GC.SuppressFinalize(this);
}
public virtual bool IsAlive {
get { return (handle.Target != null); }
}
public virtual bool TrackResurrection {
get { return this.trackResurrection; }
}
public virtual T Target {
get {
object o = handle.Target;
if ((o == null) || (!(o is T)))
return default(T);
else
return (T)o;
}
set {
handle = GCHandle.Alloc(value,
this.trackResurrection ? GCHandleType.WeakTrackResurrection : GCHandleType.Weak);
}
}
}
I've allowed Target to be settable against my better judgement to bring it more in like with WeakReference. It's still not serializable though unlike WeakReference.
Reference URL: http://damieng.com/blog/2006/08/01/implementingweakreferencet
No comments:
Post a Comment