c# - 我无法捕获的 IOException

标签 c# serial-port ioexception

我有一个与 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()

最佳答案

我不完全确定它是否适用于此,但有一些机制可以在应用程序域级别捕获整体崩溃 - http://msdn.microsoft.com/en-GB/library/system.appdomain.unhandledexception.aspx

(不是关于其他事件的部分,例如 ThreadException - 这些可能需要它们自己的处理程序,具体取决于情况)

关于c# - 我无法捕获的 IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14959425/

相关文章:

c# - 使用重载的构造函数实例化泛型类型

c# - 为什么 ContextMenu Command 和 CommandParameter 在 DataGrid 中不起作用

c++ - Linux串口RAW模式

hadoop - 运行 Map Reduce 作业显示错误 - Mkdirs 无法创建/var/folders/

java - 未报告的异常 java.io.IOException at actionlistener

c# - 使用 C# 在 Dynamics CRM 中合并联系人

c# - EF4 代码优先导致 InvalidOperationException

c - 在嵌入式 c 中通过 RS232 处理 ASCII 命令

c - IrDA 发现的默认设置(波特率、位、停止、奇偶校验、流量控制等)

c# - 由于 IOException,无法删除文件。它正在被另一个进程使用