Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with SerialPort

I'm working with SerialPort to communicate (read only) with barcode reader.

I've installed driver to operate with the reader as if it was connected via Com-port, though it is a usb device. When the device is plugged, one more Com-port appears in the list.

The problem is the following. I initialize the SerialPort object to read from barcode reader, but if the reader is unplugged, I have no way to finalize or dispose the SerialPort object correctly, because the port it is "attached" to no longer exists.

The result is WinIOException when the program is closed. I cannot catch it not only in the code working with the SerialPort but at the program.cs level as well. According to the stack WinIOException is thrown after the attempts of finalizing and disposing the SerialPort object.

Are there any ideas how I can operate with this situation properly? Or at least to catch the exception?

The thing I know for sure is that the problem is not in this particular driver; I had one more barcode reader from another manufacturer (with the same purpose driver) - the situation is the same.

like image 529
26071986 Avatar asked Jul 12 '10 16:07

26071986


1 Answers

Sigh, this an age old problem with USB serial port emulators. Serial ports are devices that date from the stone age. They used to be screwed into the bus, no way to remove them while a program is using it without drawing sparks and billowing smoke. Stone age also includes the lack for any kind of plug-and-play support so that a program could detect that the device is suddenly gonzo.

Unfortunately, the majority of the crummy device drivers that emulate them just make them disappear, even though a program has the port opened. This works just about as well as jerking a flash drive out of the socket when Windows is writing files to it. There's a background worker thread that waits for notifications from the device driver so that it can generate the DataReceived, ErrorReceived and PinChanged events. That thread suffers a heart attack when the device suddenly disappears. You can't catch that, it is a thread that was started by the SerialPort class, you can't wrap it with try/catch.

By popular demand, Microsoft did something about it in .NET 4.0. Not actually sure what happens in that release. If you're stuck on an earlier release, the only reasonable thing you can do is tape a sign next to the USB slot: "Don't remove while in use!" Which inevitably makes somebody unplug the device at least twice to see what happens. After which they get bored with that and leave you in peace.

The very unreasonable workaround is an app.exe.config file with this content:

<?xml version ="1.0"?>
<configuration>
  <runtime>
    <legacyUnhandledExceptionPolicy enabled="1"/>
  </runtime>
</configuration>

Don't use it.

like image 127
Hans Passant Avatar answered Oct 03 '22 07:10

Hans Passant