.NET 4串行端口的ObjectDisposedException在Windows 7只串行、端口、NET、ObjectDisposedException

2023-09-02 21:46:20 作者:爲何我還想他。

这是一个问题,我以前都在.NET 2.0串口类的时间。有人建议,在升级到.NET 4将解决这个问题......它确实在几乎所有情况下。

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.

如果我使用内置到.NET串口类与USB转串口适配器通信,适配器是意外拔出,而端口是开放的,有时我得到一个未处理的异常:

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?

编辑:我能够重现问题喽。我尝试了,但还是很为难,什么在.NET 4.0中导致此错误。

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.

编辑2:这似乎的只有的发生在Windows 7上拔下并插上USB转串口适配器在XP精美的作品

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

推荐答案

看来,这个错误不会被微软在短期内固定的,有没有好的解决办法。我已经用了一年以上的工作在这个问题上偏离和式。

It seems that this bug won't be fixed by Microsoft any time soon, and that there is no good workaround. I've spent over a year working on this problem off-and-on.

我的解决方案是使用一个第三方组件。测试15+后,我发现,只有一个真正的工作原理是CommStudio。

The solution for me was to use a 3rd party component. After testing 15+, I've found that the only one that really works is CommStudio.

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

The free express version is here: http://www.componentsource.com/products/commstudio/downloads.html?rv=42917