views:

30

answers:

0

This is a problem I used to have all the time with the serial port class in .NET 2.0. It was suggested that upgrading to .NET 4 would fix the problem... and it did in almost all cases.

If I am using the serial port class built-in to .NET to communicate with a USB-to-serial adapter, and the adapter is unexpectedly unplugged while the port is open, on occasion I get an unhandled exception:

Application: test.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.ObjectDisposedException
Stack:
   at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean ByRef)
   at System.StubHelpers.StubHelpers.SafeHandleAddRef(System.Runtime.InteropServices.SafeHandle, Boolean ByRef)
   at Microsoft.Win32.UnsafeNativeMethods.GetOverlappedResult(Microsoft.Win32.SafeHandles.SafeFileHandle, System.Threading.NativeOverlapped*, Int32 ByRef, Boolean)
   at System.IO.Ports.SerialStream+EventLoopRunner.WaitForCommEvent()
   at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ThreadHelper.ThreadStart()

Again, most of the time it works fine. In fact, I can't even reproduce the problem on my own computers. This happens to a friend of mine. Is there any way at all to trap this error?

Edit: I was able to reproduce the behavior myself. I am experimenting now, but still am stumped as to what causes this error in .NET 4.0.

Edit 2: This seems to only happen on Windows 7. Unplugging and plugging in the USB-to-serial adapter on XP works beautifully.