title: How do I properly close serial port connection and thread it runs in?
body: <p>I have an serial port read running on a background thread, but everytime I try to close it, I get an exception. Usually an IO-exception.</p>
  
  <p>It is as if the read continues on eventhough I close the thread.</p>
  
  <p>This is my current code:</p>
  
  <p>EDIT: I changed the code, removed the checks on threatstate.</p>
  
  <pre><code>public bool Connect(string portName)
      {
          try
          {
              sp = new SerialPort(portName, BaudRate);
              sp.Open();
              sp.DtrEnable = true;
  
               cf = SingletonFormProvider.GetInstance&lt;ConnectionForm&gt;(null);
  
              _continue = true;
              readThread = new Thread(Read);
              readThread.Start();
  
              return true;
          }
          catch(Exception ex)
          { 
              MessageBox.Show(ex.Message);
  
              return false;
          }
      }
  
      public void Disconnect()
      {
  
          if (IsConnectionOpen)
          {
              _continue = false;
              readThread.Abort();
  
              while (readThread.ThreadState == ThreadState.AbortRequested)
              { }
  
              sp.Close();
  
              readThread.Join();
          }
  
      }
  
      private void Read()
      {
  
                  while (_continue)
                  {
                      try
                      {
                          string message = sp.ReadLine();
                          cf.WriteLog(message);
                      }
                      catch (Exception ex)
                      {
  
                              MessageBox.Show(ex.Message);
                              _continue = false;
                              readThread.Join();
                              sp.Close();
  
                      }
  
              }
  
  
      }
  </code></pre>