Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all articles
Browse latest Browse all 8156

IO operation aborted error thrown while reading serial port using System.IO.Ports.SerialPort class

$
0
0

I am trying to read data written by an external device (weighing scale in this case) connected to serial port using .Net 4.0 - SerialPort class.

First we initialize the serial port as below:

InitializeSerialPort()
{
   if ((serialPort != null) && (serialPort.IsOpen))
        {
            serialPort.Close();
            serialPort.Dispose();
            serialPort = null;
        }

        serialPort = new SerialPort("COM2", 9600, Parity.None, 8,
                         StopBits.One) { Handshake = Handshake.None };
        serialPort.DataReceived += serialPort_DataReceived;
        serialPort.NewLine = "\r";
}

We are using background worker thread to poll the device on continuous interval by sending a command (understood by the weighing scale) on the serial port. As soon as we send the command the device connected to serial port reacts with a response output. We call ReadLine API of SerialPort class to get the data present on the serial port written by the device in the DataReceived event as shown in the code snippet below :

private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { data = serialPort.ReadLine(); // throws IO error } catch(System.IO.IOException ex) { //since serial port reading threw an error so

//there is no value to be parsed hence exit the function. return; } //if no error then parse the data received }

I'm using System.IO.Ports.SerialPort class of .Net framework 4.0. I can see a number of people posting this issue on other forums but with no specific resolution. Some of them terming .Net Serial port class as buggy which has not been fixed by Microsoft till date.

I also tried the solution posted on msdn forums but no success. I need some input if any one else has come across this issue or its resolution.

Thanks in advance.



Viewing all articles
Browse latest Browse all 8156

Trending Articles