我有一个与 USB-GPS 通话的应用程序。如果没有什么不寻常的事情发生,它就像一种魅力。但我有一个大问题。如果 USB 被拔出,我的程序(有时)会崩溃。我在需要它们的地方有 Try/Catch,但这个 IOExeption 没有被抓住。我只是得到“设备无法识别命令”并且程序停止。这是启动端口的代码:
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()