title: Using WeakReference to resolve issue with .NET unregistered event handlers causing memory leaks
body: <p>The problem:  Registered event handlers create a reference from the event to the event handler's instance.  If that instance fails to unregister the event handler (via Dispose, presumably), then the instance memory will not be freed by the garbage collector.  </p>
  
  <p>Example:</p>
  
  <pre><code>    class Foo
      {
          public event Action AnEvent;
          public void DoEvent()
          {
              if (AnEvent != null)
                  AnEvent();
          }
      }        
      class Bar
      {
          public Bar(Foo l)
          {
              l.AnEvent += l_AnEvent;
          }
  
          void l_AnEvent()
          {
  
          }            
      }
  </code></pre>
  
  <p>If I instantiate a Foo, and pass this to a new Bar constructor, then let go of the Bar object, it will not be freed by the garbage collector because of the AnEvent registration.</p>
  
  <p>I consider this a memory leak, and seems just like my old C++ days.  I can, of course, make Bar IDisposable, unregister the event in the Dispose() method, and make sure to call Dispose() on instances of it, but why should I have to do this?</p>
  
  <p>I first question why events are implemented with strong references?  Why not use weak references?  An event is used to abstractly notify an object of changes in another object.  It seems to me that if the event handler's instance is no longer in use (i.e., there are no non-event references to the object), then any events that it is registered with should automatically be unregistered.  What am I missing?</p>
  
  <p>I have looked at WeakEventManager.  Wow, what a pain.  Not only is it very difficult to use, but its documentation is inadequate (see <a href="http://msdn.microsoft.com/en-us/library/system.windows.weakeventmanager.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.weakeventmanager.aspx</a> -- noticing the "Notes to Inheritors" section that has 6 vaguely described bullets).</p>
  
  <p>I have seen other discussions in various places, but nothing I felt I could use.  I propose a simpler solution based on WeakReference, as described here.  My question is:  Does this not meet the requirements with significantly less complexity?</p>
  
  <p>To use the solution, the above code is modified as follows:</p>
  
  <pre><code>    class Foo
      {
          public WeakReferenceEvent AnEvent = new WeakReferenceEvent();
  
          internal void DoEvent()
          {
              AnEvent.Invoke();
          }
      }
  
      class Bar
      {
          public Bar(Foo l)
          {
              l.AnEvent += l_AnEvent;
          }
  
          void l_AnEvent()
          {
  
          }
      }
  </code></pre>
  
  <p>Notice two things:
  1. The Foo class is modified in two ways:  The event is replaced with an instance of WeakReferenceEvent, shown below; and the invocation of the event is changed.
  2. The Bar class is UNCHANGED.</p>
  
  <p>No need to subclass WeakEventManager, implement IWeakEventListener, etc.</p>
  
  <p>OK, so on to the implementation of WeakReferenceEvent.  This is shown here.  Note that it uses the generic WeakReference&lt;T&gt; that I borrowed from here: <a href="http://damieng.com/blog/2006/08/01/implementingweakreferencet" rel="noreferrer">http://damieng.com/blog/2006/08/01/implementingweakreferencet</a></p>
  
  <pre><code>class WeakReferenceEvent
  {
      public static WeakReferenceEvent operator +(WeakReferenceEvent wre, Action handler)
      {
          wre._delegates.Add(new WeakReference&lt;Action&gt;(handler));
          return wre;
      }
  
      List&lt;WeakReference&lt;Action&gt;&gt; _delegates = new List&lt;WeakReference&lt;Action&gt;&gt;();
  
      internal void Invoke()
      {
          List&lt;WeakReference&lt;Action&gt;&gt; toRemove = null;
          foreach (var del in _delegates)
          {
              if (del.IsAlive)
                  del.Target();
              else
              {
                  if (toRemove == null)
                      toRemove = new List&lt;WeakReference&lt;Action&gt;&gt;();
                  toRemove.Add(del);
              }
          }
          if (toRemove != null)
              foreach (var del in toRemove)
                  _delegates.Remove(del);
      }
  }
  </code></pre>
  
  <p>It's functionality is trivial.  I override operator + to get the += syntactic sugar matching events.  This creates WeakReferences to the Action delegate.  This allows the garbage collector to free the event target object (Bar in this example) when nobody else is holding on to it.</p>
  
  <p>In the Invoke() method, simply run through the weak references and call their Target Action.  If any dead (i.e., garbage collected) references are found, remove them from the list.</p>
  
  <p>Of course, this only works with delegates of type Action.  I tried making this generic, but ran into the missing where T : delegate in C#!</p>
  
  <p>As an alternative, simply modify class WeakReferenceEvent to be a WeakReferenceEvent&lt;T&gt;, and replace the Action with Action&lt;T&gt;.  Fix the compiler errors and you have a class that can be used like so:</p>
  
  <pre><code>    class Foo
      {
          public WeakReferenceEvent&lt;int&gt; AnEvent = new WeakReferenceEvent&lt;int&gt;();
  
          internal void DoEvent()
          {
              AnEvent.Invoke(5);
          }
      }
  </code></pre>
  
  <p>The full code with &lt;T&gt;, and the operator - (for removing events) is shown here:</p>
  
  <pre><code>class WeakReferenceEvent&lt;T&gt;
  {
      public static WeakReferenceEvent&lt;T&gt; operator +(WeakReferenceEvent&lt;T&gt; wre, Action&lt;T&gt; handler)
      {
          wre.Add(handler);
          return wre;
      }
      private void Add(Action&lt;T&gt; handler)
      {
          foreach (var del in _delegates)
              if (del.Target == handler)
                  return;
          _delegates.Add(new WeakReference&lt;Action&lt;T&gt;&gt;(handler));
      }
  
      public static WeakReferenceEvent&lt;T&gt; operator -(WeakReferenceEvent&lt;T&gt; wre, Action&lt;T&gt; handler)
      {
          wre.Remove(handler);
          return wre;
      }
      private void Remove(Action&lt;T&gt; handler)
      {
          foreach (var del in _delegates)
              if (del.Target == handler)
              {
                  _delegates.Remove(del);
                  return;
              }
      }
  
      List&lt;WeakReference&lt;Action&lt;T&gt;&gt;&gt; _delegates = new List&lt;WeakReference&lt;Action&lt;T&gt;&gt;&gt;();
  
      internal void Invoke(T arg)
      {
          List&lt;WeakReference&lt;Action&lt;T&gt;&gt;&gt; toRemove = null;
          foreach (var del in _delegates)
          {
              if (del.IsAlive)
                  del.Target(arg);
              else
              {
                  if (toRemove == null)
                      toRemove = new List&lt;WeakReference&lt;Action&lt;T&gt;&gt;&gt;();
                  toRemove.Add(del);
              }
          }
          if (toRemove != null)
              foreach (var del in toRemove)
                  _delegates.Remove(del);
      }
  }
  </code></pre>
  
  <p>Hopefully this will help someone else when they run into the mystery event caused memory leak in a garbage collected world!</p>