Reputation: 1350
I have an serial port read running on a background thread, but everytime I try to close it, I get an exception. Usually an IO-exception.
It is as if the read continues on eventhough I close the thread.
This is my current code:
EDIT: I changed the code, removed the checks on threatstate.
public bool Connect(string portName)
{
try
{
sp = new SerialPort(portName, BaudRate);
sp.Open();
sp.DtrEnable = true;
cf = SingletonFormProvider.GetInstance<ConnectionForm>(null);
_continue = true;
readThread = new Thread(Read);
readThread.Start();
return true;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public void Disconnect()
{
if (IsConnectionOpen)
{
_continue = false;
readThread.Abort();
while (readThread.ThreadState == ThreadState.AbortRequested)
{ }
sp.Close();
readThread.Join();
}
}
private void Read()
{
while (_continue)
{
try
{
string message = sp.ReadLine();
cf.WriteLog(message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_continue = false;
readThread.Join();
sp.Close();
}
}
}
Upvotes: 1
Views: 3258
Reputation: 1286
Join your read thread before you close the serial port:
public void Disconnect()
{
if (IsConnectionOpen)
{
_continue = false;
readThread.Join();
sp.Close();
}
}
Upvotes: 0
Reputation: 28839
You do know that what thread.Abort() does is throw a ThreadAbortException in the thread in question, right? In the thread you catch all exceptions that inherited from Exception. I believe that includes the abort exception. If you really must call Abort, you may want to close the serial port first since I believe that will cause any pending calls to return.
Upvotes: 2