SerialPort.Close report exception

  • Thread starter Thread starter Likevin33
  • Start date Start date
L

Likevin33

Guest
I write an software using c# in VS2017. My software run on windows 10,64bits pc, and it will communicate with another device using rs422, whick will convert to a usb to connected with my pc. And the device will send message to me every 0.5 second.
So I use SerialPort class to do the commnunicate work.
In order to support Hot Plug, in my software, I use a thread to watch it. The thread will creat the SerialPort object to communicate, and then it will create a timer to watch. If my software doesn't receive data from seral port for 3 seconds( normally every 0.5 seconds receive datas), the thread will do check, if it finds a serial port, it will check if it's open, if open it will close it and reopen.e are show as below:


//------------------------------ my software code ------------
//this is my monitor pocesser, if my software can't receive data in 3 seconds, monitor will run
public void Monitor()
{
string[] portNames = SerialPort.GetPortNames();
foreach (string portName in portNames)
{
bool iniResult = SerialPortInit(portName);
if (iniResult)
{
break;
}
}
}


//this do the serial port initail work
public bool SerialPortInit(string portName)
{
try
{
if (m_serialPort == null)
{
m_serialPort = new SerialPort(portName, 9600, Parity.None, 8, StopBits.One);
m_serialPort.ErrorReceived += M_serialPort_ErrorReceived;
m_serialPort.ReadBufferSize = 200;
m_serialPort.WriteBufferSize = 200;
m_serialPort.ReceivedBytesThreshold = 1;
m_serialPort.ReadTimeout = 500;
m_serialPort.WriteTimeout = 500;
m_serialPort.DataReceived += new SerialDataReceivedEventHandler(SerialPortDataReceived);
}
else
{
if (m_serialPort.IsOpen)
{
m_serialPort.Close(); //here throw the exception
}
m_serialPort.PortName = portName;
}
m_serialPort.Open();
return true;
}
catch (Exception e)
{
//here the catch the exception
return false;
}
}
//------------------------------end of my software code ------------


When my software do communicate with the device, there may be some hardware serialpot problem.

My software can't receive data for 3 seconds, so the above monitor works, and when I debug, I find it run the following code:
m_serialPort.Close();
here report the exception, the exception info is as below, but I can't find the exception in the msdn: here .


So why this happens, and what shall I do.

Thanks a lot!

Ps: It seems the pictures below may be not clear, and I have reported the issure here: here

1621035.png1621036.png1621037.png

Continue reading...
 
Back
Top