title: C# Handling a Serial Port when program is closing
body: <p>I'm building an app in C# that runs with Excel, the end game is to allow users to click a button on an excel sheet, which then sends some commands down the serial port, and then reads back data.</p>
  
  <p>This is done and works fine.</p>
  
  <p>My question is, how can I check to make sure that no events / functions are being ran on the <code>serialport_DataReceived;</code> event before the application closes, as if they are then I will get an exception crash - </p>
  
  <p><code>The I/O operation has been aborted because of either a thread exit or an application request.</code></p>
  
  <p>So, in a way I need to run some sort of clean up stating that is the serial port is still gathering data, wait until that has finished before closing down.</p>
  
  <p>This is my code so far;</p>
  
  <pre><code>     while (!dataCollected)
       {
          if (data.Contains(carrier)) // If the read data doesn't contain end carriage return, then retry until it does
          {
               if (data.Contains(resultMessage)) // Check to make sure it has the result message - this guarantees a fully built read data with no missing bytes 
               {
                   ParseIncomingDataToExcel(data); // put the string into a specfic excel row
                   dataCollected = true; // exits out of the while loop
               }
          }
          else // Carriage not found, data loss - try again
          {
              data = wrench.ReadLine();
          }
  }
  
  
  if (dataCollected)
      SetControlPropertyValue(button, "Enabled", true); // Invoke to turn the button enabled to true
  </code></pre>
  
  <p>So basically, you send a command via serial and then get an output. If you try and exit during this process then it will give an exception (I know this will happen, I would rather put the code in to stop it from happening rather then just putting it in a try block</p>
  
  <pre><code>private void Sheet1_Shutdown(object sender, System.EventArgs e)
  {
       dataCollected = true;
       wrench.Close();
  }
  </code></pre>
  
  <p>This makes the program hang when trying to close a connection on the serial port... If I remove the wrench.close - then the above exception is show (As I expected).</p>
  
  <p>--EDIT--</p>
  
  <p>I've tried declaring my boolean values in my while loop to a global volatile type, but I just have a bad feeling with using something like this, seems like a hack (and still doesn't work, just hangs...)</p>