title: How to safely dispose CCR Dispatcher, DispatcherQueue and Interleave
body: <p>I am trying to find the best way to dispose the CCR Dispatcher, DispatcherQueue and Interleave which are interlinked to each other. I have a class say "MyClass" that has a single dispatcher and a single dispatcher queue. The class exposes a single PortSet to which clients can post messages to. In "MyClass", I have created persistent receivers for those messages and attached to the dispatcher queue. I have also added all the receivers as part of a single Interleave. Now when the client thinks it is done using "MyClass" class, I want the client to destroy the class safely. There are three things that needs to destroy here which are the dispatcher, the dispatcher queue and the interleave. What is the best way to do that? I happened to read the discussions in the link <a href="http://channel9.msdn.com/shows/Going+Deep/CCR-Programming-Jeffrey-Richter-and-George-Chrysanthakopoulos/" rel="nofollow">http://channel9.msdn.com/shows/Going+Deep/CCR-Programming-Jeffrey-Richter-and-George-Chrysanthakopoulos/</a>. Although, not mentioned explicitly, I inferred that the right way to Dispose is that I need to first post a tear down message to the interleave, wait for the interleave to teardown then dispose the dispatcher queue. Now, the dispose code of my class will look like the following.</p>
  
  <pre><code>var teardownInterleave = new TeardownInterleave();
  InternalMessagesPort.PostUnknownType(teardownInterleave);
  var done = new ManualResetEvent(false);
  Activate(Arbiter.Receive(false, teardownInterleave.CompletionPort,
      emptyValue =&gt; done.Set()));
  done.WaitOne();
  Thread.Sleep(100);
  
  // Dispose the TaskQ
  TaskQueue.Dispose();
  
  /// &lt;summary&gt;
  /// Message posted to any interleave asking it to teardown.
  /// &lt;/summary&gt;
  public sealed class TeardownInterleave
  {
      /// &lt;summary&gt;
      /// Gets the completion port.
      /// &lt;/summary&gt;
      /// &lt;value&gt;
      /// The completion port.
      /// &lt;/value&gt;
      public Port&lt;EmptyValue&gt; CompletionPort { get; private set; }
  
      /// &lt;summary&gt;
      /// Initializes a new instance of the &lt;see cref="TeardownInterleave" /&gt; class.
      /// &lt;/summary&gt;
      public TeardownInterleave()
      {
          CompletionPort = new Port&lt;EmptyValue&gt;();
      }
  }
  </code></pre>
  
  <p>Please clarify if this is the right approach or am I missing something.</p>
  
  <p>Thanks,</p>
  
  <p>Venkat</p>