关闭申请期间未知的“IO异常未处理”来源

时间:2013-02-19 13:20:04

标签: c# serial-port ioexception

我正在尝试防止在我的应用程序中使用串行连接的用户的任何奇怪行为。

我的应用程序通过 USB->串行转换器连接到设备。在我确定端口可用,已连接并准备就绪后,我正在设置环境以发送数据,但如果有任何用户拔下通信电缆,我也想准备好,以便使用以下代码。

try
{
  serialPort.WriteLine("BT\r"); 
}
catch (IOException ioe)
{
  Console.WriteLine(ioe.Message);
  currentCommunicationState = DEVICE_COMMUNICATION_STATES.IDLE;
  // other stuff which set application in idle mode; buttons statuses, etc
}

上述例外处理得很好。应用程序进入空闲模式,我可以使用它,但是...当我关闭应用程序时,我得到下一个异常没有任何指定的细节。我无法找到抛出第二个异常的地方或如何保留这种情况。

System.IO.IOException was unhandled
Message="Specified port doesn't exist"
Source="System"
StackTrace:
   w System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str)
   w System.IO.Ports.SerialStream.Dispose(Boolean disposing)
   w System.IO.Ports.SerialStream.Finalize()
InnerException:

从控制台登录

Port 'COM29' nie istnieje. \\port COM28 doesn't exist - called from my exception handler
A first chance exception of type 'System.IO.IOException' occurred in System.dll
The thread 0x14d4 has exited with code 0 (0x0).
The thread 0x1e98 has exited with code 0 (0x0).

2 个答案:

答案 0 :(得分:0)

当抛出第一个异常时,您需要摆脱用于通信的SerialStream。你得到的例外是尝试处理该流的程序。

在异常处理程序中,关闭串口流。

答案 1 :(得分:0)

this post has some information似乎有关此问题。简而言之,端口的Dispose方法是错误的,因此它会导致终结器中的错误。 IMO这是一种错误行为。

如果您确定在正确的时间处理了所有内容并且仍然遇到此问题,则应该对Port类进行子类化,以便在覆盖Dispose(bool disposing)方法时进行更强大的错误处理。您可以将基类调用包装在try / catch中。