title: How to release anonymous delegates / closures correctly in C#?
body: <p>I'm working on a GUI application, which relies heavily on <code>Action&lt;&gt;</code> delegates to customize behavior of our UI tools. I'm wondering if the way we are doing this has any potential issues, e.g. whether the implementation keeps references to captured variables, class instances that declare the delegates etc? </p>
  
  <p>So let's say we have this class <code>MapControl</code>, which wraps a stateful GUI control. The map has different kinds of tools (Drawing, Selection, etc.), represented by <code>ITool</code> interface. You can set the tool with <code>StartTool()</code>, but you can only have one tool active at a time, so when another tool is set previous one is stopped using <code>StopTool()</code>. When tool is stopped, a caller-specified callback delegate is executed.</p>
  
  <pre><code>public class MapControl
  {
      ITool _currentTool;
      Action&lt;IResult&gt; _onComplete;
  
      public void StartTool(ToolEnum tool, Action&lt;IResult&gt; onComplete) {
  
          //If tool is active, stop it first
          if (_currentTool != null) StopTool();
  
          _onComplete = onComplete;
  
          //Creates a tool class, etc.
          _currentTool = CreateTool(tool) as ITool;
      }
  
      public void StopTool() {
  
          //Execute callback delegate
          IResult result = _currentTool.GetResult();
          if (_onComplete != null)
              _onComplete(result);
  
          //Nix the references to callback and tool
          _onComplete = null;
          _currentTool = null;
      }
  }
  </code></pre>
  
  <p>In the application's <code>ViewModel</code> class we set some tool like this:</p>
  
  <pre><code>class ViewModel
  {
      private MapControl _mapControl = new MapControl();
      public void SetSomeTool() 
      {
          //These variables will be captured in the closure
          var someClassResource = this.SomeClassResource;
          var someLocalResource = new object();
  
          //Start tool, specify callback delegate as lambda
          _mapControl.StartTool(ToolEnum.SelectTool, (IResult result) =&gt; {
  
              //Do something with result and the captured variables
              someClassResource.DoSomething(result, someLocalResource);
          });
      }
  }
  </code></pre>
  
  <p>In our case the <code>ViewModel</code> class is attached to the main window of a WPF application, and there can only be one instance of <code>ViewModel</code> during the application lifetime. Would it change anything if this weren't the case, and the classes which declare the delegates would be more transient?</p>
  
  <p>My question is, am I disposing of the callback delegates correctly? Are there any scenarios, where this can cause memory bloat by holding on to references it shouldn't?</p>
  
  <p>More generally, what's the safe and correct way of disposing anonymous delegates?</p>