title: Detect when a COM Object goes out of Scope
body: <p>I have a .NET Component that is being exposed to COM.</p>
  
  <p>This component has a thread running internally that connects to a named pipe, and handles disconnects from the pipe and reconnects as needed.</p>
  
  <p>The thread runs for the lifetime of the instance of the component that was instantiated inside the COM Program (vb6 in this instance).</p>
  
  <p>If the COM application is shutting down, but not calling my "Close" method that gracefully shuts down the thread (and pipe), is there a way to detect that they are closing the application down so that I do not need to rely on them following the rules properly?</p>
  
  <p>The thread has it's ISBackground = true set.</p>
  
  <p>This is the basic parts of my Thread</p>
  
  <pre><code>private System.IO.Pipes.NamedPipeClientStream mPipe;
  private System.Threading.AutoResetEvent mConnectedHold;
  
  private void ConnectPipe()
  {
      while (mRunning)
      {
          try
          {
              mConnecting = true;
              mConnected = false;
              if (mPipe != null)
              {
                  mPipe.Close();
                  mPipe.Dispose();
              }
              mPipe = new System.IO.Pipes.NamedPipeClientStream(@".", @"MyPipe", System.IO.Pipes.PipeDirection.InOut, System.IO.Pipes.PipeOptions.Asynchronous);
              mPipe.Connect(1000);
  
              mConnecting = false;
              mConnected = true;
  
              mPipe.BeginRead(mBuffer, 0, mBuffer.Length, new AsyncCallback(ReadPipe), null);
  
              mConnectedHold.WaitOne();
          }
          catch (TimeoutException ex)
          {
          System.Diagnostics.Debug.Print("Not connected yet");
          }
          catch (Exception ex)
          {
              mRunning = false;
          }
      }
  }
  </code></pre>
  
  <p>and the close is fairly basic.</p>
  
  <pre><code>public void Close()
  {
      mRunning = false;
      if (mPipe != null )
      {
          mPipe.Close()
          mPipe.Dispose()
      }
      mConnected = false;
  }
  </code></pre>