1

I'm trying to prevent against of any strange behaviour of users who use serial connection in my application.

My application connects to device over USB->serial converter. After I'm sure that port is available, connected and ready I'm seting enviroment to send data, but I also want to be ready if any user will unplug the communication cable so I use following code.

try
{
  serialPort.WriteLine("BT\r"); 
}
catch (IOException ioe)
{
  Console.WriteLine(ioe.Message);
  currentCommunicationState = DEVICE_COMMUNICATION_STATES.IDLE;
  // other stuff which set application in idle mode; buttons statuses, etc
}

The exception above is handled well. Applications goes to idle mode and I'm able to use it, but... when I close the application I get next exception without any more specified details. I cannot find place where this second exception is thrown or how to preserve this situation.

System.IO.IOException was unhandled
Message="Specified port doesn't exist"
Source="System"
StackTrace:
   w System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str)
   w System.IO.Ports.SerialStream.Dispose(Boolean disposing)
   w System.IO.Ports.SerialStream.Finalize()
InnerException:

Log from console

Port 'COM29' nie istnieje. \\port COM28 doesn't exist - called from my exception handler
A first chance exception of type 'System.IO.IOException' occurred in System.dll
The thread 0x14d4 has exited with code 0 (0x0).
The thread 0x1e98 has exited with code 0 (0x0).
h__
  • 761
  • 3
  • 12
  • 41
  • possible duplicate of [Releasing a unplugged virtual Serial Port](http://stackoverflow.com/questions/9835881/releasing-a-unplugged-virtual-serial-port) – Hans Passant Feb 19 '13 at 13:30
  • Also: http://stackoverflow.com/questions/3230311/problem-with-serialport/3230950#3230950 – Hans Passant Feb 19 '13 at 13:30

2 Answers2

0

When the first exception is thrown, you need to get rid of the SerialStream you're using for the communication. The exception you're getting is the program trying to dispose of that stream.

In your exception handler, close the serial port stream.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
  • But I don't use SerialStreamer - everything what I send in this case/momenent is just BT\r which finaly is not send. Then I'm trying to close app. So more detailed: Open port Send BT // handled Disconnect cable Close aplication // not handled – h__ Feb 19 '13 at 13:34
0

It appears that this post has some information about the issue. In short, the Dispose method of the port is buggy, such that it causes errors in the finalizer. IMO this is buggy behaviour.

If you're sure that you disposed of everything at the right time and you're still getting this problem, you should subclass the Port class to put some more robust error handling in an override of the Dispose(bool disposing) method. You can wrap the base class call in a bit of try/catch.

spender
  • 117,338
  • 33
  • 229
  • 351