IOException我无法捕捉到
我有一个应用程序与USB-GPS通话。如果没有什么不寻常的事情,它就会变成一种魅力。但是我有一个很大的问题。如果USB被拔出,我的程序(有时)会崩溃。我有Try/Catch在哪里需要它们,但是这个IOExeption不会被捕获。我只是得到“设备无法识别命令”,程序停止。下面是启动该端口的代码:IOException我无法捕捉到
public LatLongFromGPS(Form1 parent)
{
this.parent = parent;
String port;
this.SPort = new SerialPort(port, 4800);
this.SPort.ReadTimeout = 500;
this.SPort.DataReceived += new SerialDataReceivedEventHandler(dataReceived);
}
public bool checkIfPortsOpen()
{
return (this.SPort.IsOpen);
}
public void openPort()
{
try
{
if (!this.SPort.IsOpen)
{
this.SPort.Open();
}
}
catch(Exception ex)
{
parent.LoggIt.WriteLogg("OPENPORT " + ex.ToString(), Logger.LoggType.Debug);
}
}
public void dataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (SPort.IsOpen)
{
String GPGGAString;
Thread.CurrentThread.Join(200);
buffert = new char[this.SPort.BytesToRead];
this.SPort.Read(buffert, 0, buffert.Length);
GPGGAString = findStringFromGPS();
if (GPGGAString != null)
{
getLatitudefromString(GPGGAString);
getLongitudefromString(GPGGAString);
getTimeFromString(GPGGAString);
this.newData = true;
}
}
}
catch(Exception ex)
{
parent.LoggIt.WriteLogg("GPSERROR " + ex.ToString(), Logger.LoggType.Debug);
}
}
然后,我有这样的一个定时器来检查信息
if (this.LatLong.newDataReceived())
{
//DOING STUFF
}
if (!this.LatLong.checkIfPortsOpen())
this.LatLong.openPort();
任何人有任何建议,如何停止崩溃?
[编辑]堆栈:
at System.IO.Ports.InternalResources.WinIOError(Int32, System.String)
at System.IO.Ports.InternalResources.WinIOError()
at System.IO.Ports.SerialStream.Dispose(Boolean)
at System.IO.Ports.SerialStream.Finalize()
我不能完全肯定是否适用于这里,但也有机制赶上在AppDomain的水平整体崩溃 - http://msdn.microsoft.com/en-GB/library/system.appdomain.unhandledexception.aspx
(不关于其他事件的部分,例如ThreadException - 这些可能需要它们自己的处理程序,具体取决于具体情况)
“catch”是也许过度陈述它;如果你很快,你可以*记录它们,但通常它是这个阶段的终端,你的过程即将死亡 – 2013-02-19 14:11:16
尽管不是最佳实践,但顶级异常处理可能会解决您的问题。一个例子见http://richnewman.wordpress.com/2007/04/07/top-level-exception-handling-in-windows-forms-applications-%E2%80%93-code-listing-1/。
这听起来像是在工作线程上发生异常;屏幕上出现异常的'.StackTrace'是什么? (可能是在一个丑陋的错误框中) – 2013-02-19 14:12:07
您是否错误地写入'parent.LoggIt.WriteLogg(“GPSERROR”'line?log?“) – Artemix 2013-02-19 14:12:12
您是否在使用过之前设置过'port'? – 2013-02-19 14:17:09