title: Exit a windows console application to clean up resources
body: <p>I have a console application, in which I have a connection to a third party windows service on a remote server by tcp/ip.</p>
  
  <p>The call Hierarchy likes:</p>
  
  <pre><code>static class Program
  {
      [MTAThread]
      static void Main()
      {
          MyApplication.Start();
  </code></pre>
  
  <p>The <code>Start</code> method</p>
  
  <pre><code>public static void Start()
  {
      lock (SyncVar)
      {
          ThreadStart ts = new ThreadStart(MainCode);
          MainCodeThread = new Thread(ts);
          MainCodeThread.IsBackground = false;
          MainCodeThread.Start();
  </code></pre>
  
  <p>The detail of main thread has:</p>
  
  <pre><code>private static void MainCode()
  {
      try
      {
           // connect to the remote server, against a windows service 
           TelephonyServer tServer = new TelephonyServer(sIpaddress, "username", "password");
           while (true)
           {
              Task consumer = Task.Run(() =&gt;
               {
                     if (data != "")
                     {
                          ProcessEachChannel(data);
              });
  
              Task producer = Task.Run(() =&gt;
              {
                  // blah blah
              });
  </code></pre>
  
  <p>In the method <code>ProcessEachChannel</code>, we have </p>
  
  <pre><code>    public bool ProcessEachChannel(string workItem)
      {
          ChannelResource cr = tServer.GetChannel();
          // blah blah
      }
  </code></pre>
  
  <p>Now the application is working well. However if I click the red exit cross of the application or click stop debugging button from Visual Studio, the resources <code>ChannelResource cr</code> is not destroyed at all. I found the fact from the remote server service control dashboard. </p>
  
  <p>I tried some code</p>
  
  <p><code>System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
  process.Exited += new EventHandler(OnExited);</code></p>
  
  <p>It is not helpful. I heard some tricks to manage the thread by passing parameters to the main thread then set something <code>true</code> or <code>false</code> etc but just no clue.</p>