title: How to store Actions that do not prevent garbage collection of variables they use in scope
body: <p>I'm trying to fix a garbage collection problem of a MVVM application which uses the following model of Undo stack.</p>
  
  <p>The example is very minimalistic and real world code is much different, uses a factory class of undo lists per ViewModel instead of a single undolist but is representative:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Text;
  using System.Diagnostics;
  using System.Reflection;
  using System.ComponentModel;
  using System.Linq;
  
  namespace ConsoleApplication9
  {
      public class UndoList
      {
          public bool IsUndoing { get; set; }
  
          private Stack&lt;Action&gt; _undo = new Stack&lt;Action&gt;();
  
          public Stack&lt;Action&gt; Undo
          {
              get { return _undo; }
              set { _undo = value; }
          }
  
          private static UndoList _instance;
          // singleton of the undo stack
          public static UndoList Instance
          {
              get
              {
                  if (_instance == null)
                  {
                      _instance = new UndoList();
                  }
                  return _instance;
              }
          }
      }
  
      public class ViewModel : INotifyPropertyChanged
      {
          public event PropertyChangedEventHandler PropertyChanged;
  
          // execute the last undo operation
          public void Undo()
          {
              UndoList.Instance.IsUndoing = true;
              var action = UndoList.Instance.Undo.Pop();
              action();
              UndoList.Instance.IsUndoing = false;
          }
  
          // push an action into the undo stack
          public void AddUndo(Action action)
          {
              if (UndoList.Instance.IsUndoing) return;
  
              UndoList.Instance.Undo.Push(action);
          }
  
          // create push an action into the undo stack that resets a property value
          public void AddUndo(string propertyName, object oldValue)
          {
              if (UndoList.Instance.IsUndoing) return;
  
              var property = this.GetType().GetProperties().First(p =&gt; p.Name == propertyName);
  
              Action action = () =&gt;
              {
                  property.SetValue(this, oldValue, null);
              };
  
              UndoList.Instance.Undo.Push(action);
          }
      }
  
      public class TestModel : ViewModel
      {
          private bool _testProperty;
          public bool TestProperty
          {
              get
              {
                  return _testProperty;
              }
              set
              {
                  base.AddUndo("TestProperty", _testProperty);
                  _testProperty = value;
              }
          }
  
          // mock property indicating if a business action has been done for test
          private bool _hasBusinessActionBeenDone;
          public bool HasBusinessActionBeenDone
          {
              get
              {
                  return _hasBusinessActionBeenDone;
              }
              set
              {
                  _hasBusinessActionBeenDone = value;
              }
          }
  
          public void DoBusinessAction()
          {
              AddUndo(() =&gt; { inverseBusinessAction(); });
              businessAction();
          }
  
          private void businessAction()
          {
              // using fake property for brevity of example
              this.HasBusinessActionBeenDone = true;
          }
  
          private void inverseBusinessAction()
          {
              // using fake property for brevity of example
              this.HasBusinessActionBeenDone = false;
          }
  
      }
  
      class Program
      {
          static void Test()
          {
              var vm = new TestModel();
  
              // test undo of property
              vm.TestProperty = true;
              vm.Undo();
              Debug.Assert(vm.TestProperty == false);
  
              // test undo of business action
              vm.DoBusinessAction();
              vm.Undo();
              Debug.Assert(vm.HasBusinessActionBeenDone == false);
  
              // do it once more without Undo, so the undo stack has something
              vm.DoBusinessAction();
          }
  
          static void Main(string[] args)
          {
              Program.Test();
              GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
  
              // at this point UndoList.Instance.Undo
              // contains an Action which references the TestModel
              // which will never be collected...
              // in real world code knowing when to clear this is a problem
              // because it is a singleton factory class for undolists per viewmodel type
              // ideally would be to clear the list when there are no more references
              // to the viewmodel type in question, but the Actions in the list prevent that
          }
      }
  }
  </code></pre>
  
  <p>You see that when any viewModel goes out of scope the actions in the UndoList keep references to them. The real code groups various viewmodels into grouped undolists (viewModels that contain child viewmodels share the same undo stack), so it is difficult to know when and where to put the clearing.</p>
  
  <p>I was wondering if there is some method to make those actions expire if they are the only one keeping references to the variables inside them?</p>
  
  <p>Suggestions welcome!</p>