title: The I / O was aborted because of a thread end or an application request
body: <p>i have looked lots of topic about this but no result. Im building a programm, which automatically receives datafrom a measure device. I try to open/close the ComPort, sometimes it works but sometimes it throws an IOException when i close the Port. No mater what i do, this IoException still comes out.</p>
  
  <blockquote>
    <p>The I/O operation has been aborted because of either a thread exit or
    an application request.</p>
  </blockquote>
  
  <p>I think, when i close the Comport while the program still receiving and working on data from the measure device, and that cause Exception. Or maybe because of the threading? </p>
  
  <pre><code>using System;
  using System.Collections;
  using System.Collections.Generic;
  using System.IO.Ports;
  using System.Linq;
  using System.Text;
  using System.Threading;
  using System.Threading.Tasks;
  using System.Windows.Forms;
  
  class Pt340
  {
      private bool _isConnected = false;
  
      public SerialPort ComPort = new SerialPort
      {
          BaudRate = 19200,
          Parity = Parity.Odd,
          StopBits = StopBits.One,
          DataBits = 7,
          ReadTimeout = 500           
      };
  
      private  Dictionary&lt;string, string&gt; _status = new Dictionary&lt;string, string&gt;();
  
      public  void Open()
      {
          try
          {
              _isConnected = true;
              ComPort.Open();
          }
          catch (Exception ex)
          {
  
              MessageBox.Show("Connection fail!");
              MessageBox.Show(ex.ToString());
              _isConnected = false;
          }
      }
      public  void CLose()
      {
          _isConnected = false;
  
          if(ComPort.IsOpen)
          ComPort.Close();
  
      }
      private  void _command(string str)
      {
          _status = new Dictionary&lt;string, string&gt;();
          int temp = (int)str[0];
          _status.Add("RangeHex", temp.ToString("X"));
          temp = (int)str[6];
          _status.Add("FuncHex", temp.ToString("X"));
          // functions
          Dictionary&lt;int, ArrayList&gt; functions = new Dictionary&lt;int, ArrayList&gt;();
  
          //dict
          for (int i = 0; i &lt; 10; i++)
          {
              var dictArrayList = new ArrayList();
              Dictionary&lt;string, string&gt; nameDict = new Dictionary&lt;string, string&gt;();
              Dictionary&lt;string, int[]&gt; desimalDict = new Dictionary&lt;string, int[]&gt;();
              Dictionary&lt;string, string[]&gt; unitsDict = new Dictionary&lt;string, string[]&gt;();
              Dictionary&lt;string, double[]&gt; mulDict = new Dictionary&lt;string, double[]&gt;();
              //temporate variable
              string nameTemp = "";
              int[] desimalTemp = new int[] { };
              string[] unitsTemp = new string[] { };
              double[] mulTemp = new double[] { };
              int hex = 0x00;
              switch (i)
              {
                  case 0:
                      nameTemp = @"Current A (auto)";
                      desimalTemp = new int[] { 3 };
                      unitsTemp = new string[] { "A" };
                      mulTemp = new double[] { 1.0 };
                      hex = 0x30;
                      break;
                  case 1:
                      nameTemp = @"Capacitance";
                      desimalTemp = new int[] { 3, 2, 4, 3, 2, 4, 3, 2 };
                      unitsTemp = new string[] { "nF", "nF", "uF", "uF", "uF", "mF", "mF", "mF" };
                      mulTemp = new double[] { 0.000000001, 0.000000001, 0.000001, 0.000001, 0.000001, 0.001, 0.001, 0.001 };
                      hex = 0x36;
                      break;
                  case 2:
                      nameTemp = @"Diode";
                      desimalTemp = new int[] { 4 };
                      unitsTemp = new string[] { "V" };
                      mulTemp = new double[] { 1.0 };
                      hex = 0x31;
                      break;
                  case 3:
                      nameTemp = @"Current A (manual)";
                      desimalTemp = new int[] { 3 };
                      unitsTemp = new string[] { "A" };
                      mulTemp = new double[] { 1.0 };
                      hex = 0x39;
                      break;
                  case 4:
                      nameTemp = @"Frequency / Duty";
                      desimalTemp = new int[] { 3, 2, 4, 3, 2, 4, 3, 2 };
                      unitsTemp = new string[] { "Hz", "Hz", "kHz", "kHz", "kHz", "MHz", "MHz", "MHz" };
                      mulTemp = new double[] { 1.0, 1.0, 1000.0, 1000.0, 1000.0, 1000000.0, 1000000.0, 1000000.0 };
                      hex = 0x32;
                      break;
                  case 5:
                      nameTemp = @"Voltage";
                      desimalTemp = new int[] { 4, 3, 2, 1, 2 };
                      unitsTemp = new string[] { "V", "V", "V", "V", "mV" };
                      mulTemp = new double[] { 1.0, 1.0, 1.0, 1.0, 0.001 };
                      hex = 0x3b;
                      break;
                  case 6:
                      nameTemp = @"Ohm";
                      desimalTemp = new int[] { 2, 4, 3, 2, 4, 3, 2 };
                      unitsTemp = new string[] { "Ohm", "kOhm", "kOhm", "kOhm", "MOhm", "MOhm", "MOhm" };
                      mulTemp = new double[] { 1.0, 1000.0, 1000.0, 1000.0, 1000000.0, 1000000.0, 1000000.0 };
                      hex = 0x33;
                      break;
                  case 7:
                      nameTemp = @"Auto uA current";
                      desimalTemp = new int[] { 2, 1 };
                      unitsTemp = new string[] { "uA", "uA" };
                      mulTemp = new double[] { 0.000001, 0.000001 };
                      hex = 0x3d;
                      break;
                  case 8:
                      nameTemp = @"Continuity";
                      desimalTemp = new int[] { 2 };
                      unitsTemp = new string[] { "Ohm" };
                      mulTemp = new double[] { 1.0 };
                      hex = 0x35;
                      break;
                  case 9:
                      nameTemp = @"Auto mA current";
                      desimalTemp = new int[] { 3, 2 };
                      unitsTemp = new string[] { "mA", "mA" };
                      mulTemp = new double[] { 0.001, 0.001 };
                      hex = 0x3f;
                      break;
  
              }
              nameDict.Add("Name", nameTemp); dictArrayList.Add(nameDict);
              desimalDict.Add("Desimal", desimalTemp); dictArrayList.Add(desimalDict);
              unitsDict.Add("Unit", unitsTemp); dictArrayList.Add(unitsDict);
              mulDict.Add("Mul", mulTemp); dictArrayList.Add(mulDict);
              functions.Add(hex, dictArrayList);
          }
          // status bits from byte 7
  
          _status.Add("Judge", (((int)str[7] &amp; (1 &lt;&lt; 3)) != 0 ? true : false).ToString());
          _status.Add("Batt", (((int)str[7] &amp; (1 &lt;&lt; 1)) != 0 ? true : false).ToString());
          _status.Add("OL", (((int)str[7] &amp; (1 &lt;&lt; 0)) != 0 ? true : false).ToString());
          if ((((int)str[7] &amp; (1 &lt;&lt; 2)) != 0))
              _status.Add("Sign", "-");
          else
              _status.Add("Sign", "");
          //bit 8
          _status.Add("Max", (((int)str[8] &amp; (1 &lt;&lt; 3)) != 0 ? true : false).ToString());
          _status.Add("Min", (((int)str[8] &amp; (1 &lt;&lt; 2)) != 0 ? true : false).ToString());
          _status.Add("Rel", (((int)str[8] &amp; (1 &lt;&lt; 1)) != 0 ? true : false).ToString());
          //bit 9
          _status.Add("UL", (((int)str[9] &amp; (1 &lt;&lt; 3)) != 0 ? true : false).ToString());
          _status.Add("Pmax", (((int)str[9] &amp; (1 &lt;&lt; 2)) != 0 ? true : false).ToString());
          _status.Add("Pmin", (((int)str[9] &amp; (1 &lt;&lt; 1)) != 0 ? true : false).ToString());
          //bit 10
          _status.Add("DC", (((int)str[10] &amp; (1 &lt;&lt; 3)) != 0 ? true : false).ToString());
          _status.Add("AC", (((int)str[10] &amp; (1 &lt;&lt; 2)) != 0 ? true : false).ToString());
          _status.Add("Auto", (((int)str[10] &amp; (1 &lt;&lt; 1)) != 0 ? true : false).ToString());
          _status.Add("VAHz", (((int)str[10] &amp; (1 &lt;&lt; 0)) != 0 ? true : false).ToString());
          // bit 11
          _status.Add("VBar", (((int)str[11] &amp; (1 &lt;&lt; 1)) != 0 ? true : false).ToString());
          _status.Add("Hold", (((int)str[11] &amp; (1 &lt;&lt; 1)) != 0 ? true : false).ToString());
          _status.Add("LPF", (((int)str[11] &amp; (1 &lt;&lt; 0)) != 0 ? true : false).ToString());
          //
          if (functions.ContainsKey((int)str[6]))
          {
              var v = (Dictionary&lt;string, string&gt;)functions[(int)str[6]][0];
              _status.Add("Function", v["Name"]);
              int rangeIndex = (int)str[0] - 48;
              //unit
              string unit = "";
              try
              {
                  var v2 = (Dictionary&lt;string, string[]&gt;)functions[(int)str[6]][2];
                  unit = v2["Unit"][rangeIndex];
              }
              catch (Exception)
              {
                  unit = "?";
              }
              //decimal
              int dec;
              try
              {
                  var v3 = (Dictionary&lt;string, int[]&gt;)functions[(int)str[6]][1];
                  dec = v3["Desimal"][rangeIndex];
              }
              catch (Exception)
              {
                  dec = 0;
              }
              //mul
              double mul=0.0;
              try
              {
                  var v4 = (Dictionary&lt;string, double[]&gt;)functions[(int)str[6]][3];
                  mul = (double)v4["Mul"][rangeIndex];
              }
              catch (Exception)
              {
                  mul = 0;
              }
              _status.Add("Decimal", dec.ToString());
              _status.Add("Unit", unit.ToString());
  
              if (_status["Function"] == "Frequency / Duty")
                  if (_status["Judge"] == "True")
                      _status["Function"] = "Frequency";
                  else
                      _status["Function"] = "Duty";
              _status.Add("Division", Math.Pow(10, dec).ToString());
              _status.Add("RawNumber", _status["Sign"] + str.Substring(1, 5));
              Double.TryParse(str.Substring(1, 5), out double number);
              number = number / Math.Pow(10, dec);
              _status.Add("Digits", number.ToString());
              if (_status["Sign"] == "-")
                  _status["Digits"] = (-number).ToString();
              _status.Add("Measurement", _status["Digits"] + _status["Unit"]);
              if (_status["OL"] == "True")
              {
                  _status["OL"] = "OL";
                  _status["Digits"] = "0";
              }
              Double.TryParse(_status["Digits"], out double num);
              _status.Add("Value", (num * mul).ToString());
          }
  
      }
      public string GetValue() { return _status["Value"]; }
      public string GetMeasurement() { return _status["Measurement"]; }
      public string GetFunction(){return _status["Function"];
      }
      public  void Translate()
      {
  
        _command(ComPort.ReadLine());// Exception here 
  
  
  
  
      }
  
  }
  </code></pre>
  
  <blockquote>
    <p>code in form1.cs</p>
  </blockquote>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  using System.IO.Ports;
  using System.Windows.Forms;
  </code></pre>
  
  <p>namespace PeakTechApp
  {
      public partial class Form1 : Form
      {
          Pt340 pt340 = new Pt340();
          delegate void SetTextCallback(string text);
          public Form1()
          {
              InitializeComponent();
          }</p>
  
  <pre><code>    private void Form1_Load(object sender, EventArgs e)
      {
  
          string[] ArrayComPortsNames;
          ArrayComPortsNames = SerialPort.GetPortNames();
          if (ArrayComPortsNames.Length == 0) return;
          Array.Sort(ArrayComPortsNames);
          foreach (var v in ArrayComPortsNames)
              cBoxCom.Items.Add(v);
          cBoxCom.SelectedIndex = 0;
      }
      private void cBoxCom_SelectedIndexChanged(object sender, EventArgs e)
      {
          cBoxCom.Text = cBoxCom.SelectedText;
      }
      private void btnConnect_Click(object sender, EventArgs e)
      {
          if (String.IsNullOrEmpty(cBoxCom.Text)) { MessageBox.Show("Please chose one comport."); return; }
          if (btnConnect.Text == "Connect")
          {
              pt340.ComPort.PortName = cBoxCom.Text;
              pt340.Open();
              pt340.ComPort.DataReceived += new SerialDataReceivedEventHandler(_Comport_DataReceived);
              btnConnect.Text = "Close";
          }
          else if(btnConnect.Text=="Close")
          {
              pt340.CLose();
              btnConnect.Text = "Connect";
          }
      }
      private void _Comport_DataReceived(object sender, SerialDataReceivedEventArgs e)
      {
  
          pt340.Translate();
          SetText(pt340.GetValue() + "\r\n"
                  + pt340.GetMeasurement() + "\r\n" );
  
      }
      bool isClose = false;
      // show the output
      private void SetText(string text)
      {
          if (rBox.InvokeRequired &amp;&amp; isClose==false)
          {
              SetTextCallback d = new SetTextCallback(SetText);
              Invoke(d, new object[] { text });
          }
          else
          {
              rBox.Text += text;
          }
      }
  
      private void Form1_FormClosing(object sender, FormClosingEventArgs e)
      {
          pt340.ComPort.DataReceived -= new SerialDataReceivedEventHandler(_Comport_DataReceived);
          pt340.CLose();
          isClose = true;
      }
      private void rBox_TextChanged(object sender, EventArgs e)
      {
          rBox.SelectionStart = rBox.Text.Length;
          rBox.ScrollToCaret();
      }
  }
  </code></pre>
  
  <p>}</p>