Good afternoon everybody!
I have this threaded SerialPort wrapper that reads in a line from the serial port. Here is my thread’s code.
protected void ReadData()
{
SerialPort serialPort = null;
try
{
serialPort = SetupSerialPort(_serialPortSettings);
serialPort.Open();
string data;
while (serialPort.IsOpen)
{
try
{
data = serialPort.ReadLine();
if (data.Length > 0)
ReceivedData(serialPort, new ReceivedDataEventArgs(data));
}
catch (TimeoutException)
{
// No action
}
}
}
catch (ThreadAbortException)
{
if (serialPort != null)
serialPort.Close();
}
}
when I call myThread.Abort(); I get an exception (with no line or reference to code) “Safe handle has been closed”. Can anyone spot what I am doing wrong? Thanks.
By the way, I have a Start() and a Stop() that creates the thread and aborts the thread, respectfully.
I would suspect that it is because you are using Thread.Abort to end the thread – which is generally frowned upon. The thread behavior when you abort it is not predictable. Because of that, since the serial port is a wrapper over native code, there are native resources – represented by a SafeHandle in .NET – which get disposed of unexpectedly and so you get the Exception.
You can think about what happens with your thread like this:
You really should use a different method for aborting the thread so that you get a proper chance to close and dispose of the serial port.
A proper way to close your thread could be implemented using a ManualResetEvent like this:
Of course, when using the events method to stop the thread you have to be careful to include an event state check in all your long running loops or tasks. If you don’t your thread may appear not to respond to your setting the event – until it gets out of the long-running loop, or task and gets a chance to “see” that the event has been set.