Archive for WeakReference tag
Equatable Weak References
In a previous post I described a WeakReference<T> class for providing strongly-typed WeakReference objects.
One problem with the previous WeakReference<T> class is being able to use and find it within the various collection classes. This is because one WeakReference<T> is not equal to another WeakReference<T> class.
Overriding the Equals method fixes this problem at first glance however also reveals another issue.
If you override Equals you should also override the GetHashCode method so that two objects that equal each other return the same hash code. This is because some of the collection classes use hash codes to efficiently lookup items within their collection.
Normally a hash code would be calculated from the various data items that comprise the class but in our case we really only have one to go on – the Target object itself. This raises two more issues:
- The hash code should not change over the objects lifetime – difficult when your Target object can be changed.
- The hash code should be stored because the Target object might well be collected by the GC – after all that’s what this class is all about.
This doesn’t leave us with many choices at all.
We must grab the hash code from the Target object within our constructor and store it for subsequent retrieval.
Here is EquatableWeakReference<T> with the usual disclaimers as to it’s suitability for any purpose.
using System;
using System.Runtime.InteropServices;
public class EquatableWeakReference<T> : IEquatable<EquatableWeakReference<T>>, IDisposable where T : class
{
protected GCHandle handle;
protected int hashCode;
public EquatableWeakReference(T target) {
if (target == null)
throw new ArgumentNullException("target");
hashCode = target.GetHashCode();
InitializeHandle(target);
}
protected virtual void InitializeHandle(T target) {
handle = GCHandle.Alloc(target, GCHandleType.Weak);
}
~EquatableWeakReference() {
Dispose();
}
public void Dispose() {
handle.Free();
GC.SuppressFinalize(this);
}
public virtual bool IsAlive {
get { return (handle.Target != null); }
}
public virtual T Target {
get {
object o = handle.Target;
if ((o == null) || (!(o is T)))
return null;
else
return (T)o;
}
}
public override bool Equals(object other) {
if (other is EquatableWeakReference<T>)
return Equals((EquatableWeakReference<T>)other);
else
return false;
}
public override int GetHashCode() {
return hashCode;
}
public bool Equals(EquatableWeakReference<T> other) {
return ReferenceEquals(other.Target, this.Target);
}
}
[)amien
Implementing a generic WeakReference<T> in C#
A weak reference lets you hold a reference to an object that will not prevent it from being garbage collected. There are a few scenarios where this might be important – such as listening for events, caching, various MVC patterns.
.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<T> to give you a strongly typed version so it’s somewhat puzzling why .NET doesn’t.
Here is my attempt at a WeakReference<T> for .NET. It works fine in the scenarios I’ve used and performance is close to the non-generic version but a quick glance at the SSCLI code for WeakReference reveals that the standard version is a little more complicated and it’s possible there is a reason for that – most likely due to finalizer issues.
using System;
using System.Runtime.InteropServices;
public class WeakReference<T> : IDisposable {
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.
[)amien
Lapsed-listeners – Memory leaks in subscriber-publisher scenarios
I’ve been promising something .NET related for a while… here’s something!
The lapsed-listener problem
There exists a ‘gotcha’ in .NET (and other programming environment) whereby an object has subscribed to another objects published event will not be garbage collected when you expect because the environment itself holds a reference to the subscriber inside the event notification system.
Scenario
Let’s illustrate with an example:
MyBusiness Class
Encapsulates some aspect of business functionality and publishes a Changed event.
MyTreeNode Business Adapter Class
Inherits from TreeNode and takes an instance of MyBusiness in the constructor. The object signs up to the Changed event of the MyBusiness object so that it can always accurately show the correct Icon (via ImageIndex), Text and update any associated child nodes etc.
Now you happily add instances of MyTreeNodeBusinessAdapter class to your TreeView, each with the associated MyBusiness instance it should be reflecting.
The problem now arises in that if the TreeNode is removed from the TreeView with either Nodes.Remove or Nodes.Clear then the garbage collector will not be able dispose of the MyTreeNodeBusinessAdapter objects because the MyBusiness objects hold a reference to them in their event notification queues. Even worse, an inactive TreeView hangs around because the not-yet-disposed TreeNode’s are still pointing to it.
Possible solutions…
.NET Framework 3.0 has a WeakEvent pattern to make things simple!
1. MyTreeNodeBusinessAdapter listens in to TreeView events and un-subscribes when it is removed (Rejected)
TreeNode’s maintain their own internal array of child nodes which they publish under the “Nodes” property which uses the TreeNodeCollection class to just point straight back at itself calling internal methods. None are over-ridable and while they do send the message TVM_DELETEITEM to their own TreeView control it does nothing with them nor does it have methods you could implement in a subclass. (.NET Reflector is great for finding out what’s going on inside the WinForms assembly)
This would also mean every UI control you adapt would need sub-classing to override even if you could hook into the remove events.
2. Weak Events
Xavier Musy’s web log has an interesting C# class called WeakMulticastDelegate that works in a similar way to normal delegates but uses the WeakReference class in .NET to allow referencing an object that can be garbage collected.
This solution also prevents subscribers from subscribing more than once and also from subscribers throwing an exception that stops other subscribers receiving this event (in .Net an exception will break the chain).
Alas it requires that you publish an event by writing Add and Remove methods for your event – not possible directly under VB.Net but possible with the following workaround:
- Create a C Sharp Class Library project inside your solution and add the WeakMulticastDelegate code to it (remember to put using System; and using System.Reflection; at the top of the file)
- Create a new MyPublisherWorkaround class in the C Sharp project with the private WeakMulticastDelegate… and public event EventHandler… code blocks described in Xavier’s article.
- In MyPublisherWorkaround create a method to fire your event (because .NET does not let you raise events defined in a parent class) e.g:
protected internal void Changed(EventArgs e) { if (this.weakEventHandler != null) weakEventHandler.Invoke(new object[] { this, e } ); } - Add the new CSharp project to your VB.Net project reference and appropriate Imports line at the top of your VB.Net project (obviously).
- Change your MyPublisher class to inherit from MyPublisherWorkaround.
- Change your MyPublisher class to call the Changed method (or whatever you named it) instead of executing RaiseEvent directly (because of aforementioned restrictions in the .NET framework).
3. Weak Delegates
Greg Schechter on the Microsoft Avalon team has written an article about this very problem and his solution of Weak Delegates.
Our scenario would become:
- MyPublisher instance receives request to add instance of MySubscriber to event.
- MyPublisher creates new instance of own internal class derived from WeakReference.
- This WeakReference instance actually contains the reference to the target object.
- The WeakReference instance’s event handler (with the same signature) is added to the event listener.
While this works in VB.Net it has a problem in that the class derived from WeakReference requires all subscribers to either be the same class, derived from a common parent or support a specific interface that defines this event handler.
This defeats much of the point of delegates although it might be possible to rework his code so that WeakReference stores a weak reference to the given event handler and not the object implementing it.
Stepping back
WinForms is focused around the Win32 API itself and not what modern applications require from a UI when developing along Model-View-Controller patterns.
Compound controls such as TreeView and ListView should deal with interfaces such as ITreeNode and IListViewItem and then provide a concrete implementation for backwards compatibility/general use (TreeNode and ListViewItem).
This would solve some issues – check out Skybound’s VisualStyles for a free and easy to use fix for the poor theme support.
Check out the WeakEventManager in .NET 3.5 for an event mechanism that is immunte to this problem.
[)amien