Compact Framework serial port object hangs up on finalization
It looks like there is a bug in the Compact Framework 2.0 serial port implementation. It actually manifests itself in different ways. In my case it occurred when I tried closing a SQL CE connection, but tracing the problem further revealed the true offender.
When serial port is accessed via System.IO.Ports it is touching some unmanaged resources that require finalization. When the garbage collector kicks in, some finalizer hangs up and never returns effectively freezing your process. The reason it happens consistently when closing the SQL CE connection is because the GC is fired off when the last SQL connection is closed. This leads to a misconception of something being wrong with SQL CE.
Here is the call stack of the event:
mscorlib.dll!System.PInvoke.EE.GC_WaitForPendingFinalizers()
mscorlib.dll!System.GC.WaitForPendingFinalizers() + 0x5 bytes
System.Data.SqlServerCe.dll!System.Data.SqlServerCe.SqlCeConnection.ObjectLifeTimeTracker.Close() + 0x169 bytes
System.Data.SqlServerCe.dll!System.Data.SqlServerCe.SqlCeConnection.Close(bool silent = false) + 0x27 bytes
System.Data.SqlServerCe.dll!System.Data.SqlServerCe.SqlCeConnection.Close() + 0x7 bytes
There is very little information about this on the web. I could only find one post with a similar problem -
This guy is working with the barcode scanner, which ultimately is using the serial port.
I solved the problem by switching to a third-party com-port component called SerialNET by Franson (.com). It works like a charm. There are other similar components out there as well.