仅限Windows 7上的.NET 4串行端口ObjectDisposedException

Bra*_*rad 8 .net exception-handling serial-port .net-4.0

这是我曾经一直使用.NET 2.0中的串行端口类的问题.有人建议升级到.NET 4可以解决问题......几乎在所有情况下都能解决.

如果我使用.NET内置的串行端口类与USB到串行适配器通信,并且在端口打开时意外拔出适配器,有时会出现未处理的异常:

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()
Run Code Online (Sandbox Code Playgroud)

再次,大多数时候它工作正常.事实上,我甚至无法在自己的计算机上重现这个问题.这发生在我的一个朋友身上.是否有任何方法可以捕获此错误?

编辑:我能够自己重现这种行为.我现在正在进行实验,但仍然难以理解导致.NET 4.0中出现此错误的原因.

编辑2:这似乎发生在Windows 7上.在XP上拔掉并插入USB转串口适配器可以很好地工作.

Bra*_*rad 5

看来微软不会很快修复这个bug,并且没有好的解决方法.我花了一年多的时间来解决这个问题.

我的解决方案是使用第三方组件.经过15+测试后,我发现唯一真正有效的是CommStudio.

免费快递版本在这里:http: //www.componentsource.com/products/commstudio/downloads.html?rv = 42917