R – causing ObjectDisposedException from SerialPort while debugging .NET winform

.net-3.5disposeserial-portvisual-studio-2008winforms

Vista SP1
Visual Studio 2008 SP1
.NET 3.5 SP1
C#

I have a winforms app I'm playing with that uses a SerialPort object as a private variable. When the application is compiled and executed, it works great. It also works running in debug mode wihtout any breakpoints. 90% of the time when I stop at a breakpoint and try to step through code I get an 'unhandled exception ocurred' dialog with these details:

System.ObjectDisposedException was unhandled
Message="Safe handle has been closed"
Source="mscorlib"
ObjectName=""
StackTrace:
at Microsoft.Win32.Win32Native.SetEvent(SafeWaitHandle handle)
at System.Threading.EventWaitHandle.Set()
at System.IO.Ports.SerialStream.AsyncFSCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
InnerException:

The frustrating thing is, I do not have to be stepping over serial-related code! I just have to have done something with the port. So I might read a string, manipulate the string, add two numbers together, whatever, and then BANG.

Again, this works just fine when NOT debugging, or when debugging wihtout any breakpoints. There seems to be something about stopping at a breakpoint that makes the CLR dispose the SerialStream on a different thread.

There is a lot of chatter online about problems with renoving USB devices causing this. But I'm using the build-in motherboard port on COM1.

I don't think I had this issue in .NET 2.0 so I may have to go back to that…

I need to simplify the application quite a bit before I can post code – but has anyone seen behavior like this in the debugger before?

Thanks so much!

Best Answer

I had the same problem just this morning. Surprisingly, it simply has gone away when I DISABLED the following options in VS2008 Tools->Options->Debugging->General:

  • "Enable the exception assistant"
  • "Enable .NET Framework source stepping"
  • "Step over properties and operators"
  • "Enable property evaluation and other implicit function calls"

I have no idea why, but it worked for me.

Related Topic