SerialPort.Close report exception

kevin 1 Reputation point

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.
Code 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)

//this do the serial port initail work
public bool SerialPortInit(string portName)
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);
if (m_serialPort.IsOpen)
m_serialPort.Close(); //here throw the exception
m_serialPort.PortName = portName;
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 serial pot problem.
My software can't receive data for 3 second, so the above monitor works, and when I debug, I find it run the following code:
here report the exception, the exception info is as below:



So what happens, and what shall I do to the problem.
Thanks a lot!

Not Monitored
Not Monitored
Tag not monitored by Microsoft.
35,115 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jerryzy 10,556 Reputation points

    Hi @smk ,

    C# coding is currently not supported in the Q&A forums, the supported products are listed over here (more to be added later on).

    You can ask the experts in the dedicated InfoPath forum over here:

    (If the reply was helpful please don't forget to upvote or accept as answer, thank you)

    0 comments No comments