关于程序在VS环境调试闪退报错的解决方案: System.ObjectDisposedException: 已关闭 Safe handle

最近重构了代码后,启动调试时大概率会报这个错误:System.ObjectDisposedException: 已关闭 Safe handle 

检查后发现是循环打开串口后,没有主动关闭串口:如下:

1 会报错的代码

            for (int i = 0; i < portNames.Length; i++)
            {
                spWorker = new SinglePortWorker();
                if (spWorker.Connect(portNames[i]))
                {
                    sType = spWorker.Confirm_ShakeHand();
                    if (sType != SensorAgreement.ErrorNo)
                    {
                        this.spWorkerList.Add(spWorker);
                        reParas.Add(++sIdx, sType);
                    }
                }
            }

2 修改后的代码:

            for (int i = 0; i < portNames.Length; i++)
            {
                spWorker = new SinglePortWorker();
                if (spWorker.Connect(portNames[i]))
                {
                    sType = spWorker.Confirm_ShakeHand();
                    if (sType != SensorAgreement.ErrorNo)
                    {
                        this.spWorkerList.Add(spWorker);
                        reParas.Add(++sIdx, sType);
                        continue;
                    }
                }
                //主动关闭串口
                spWorker.DisConnect();
                spWorker = null;
            }

这个问题怪就怪在,程序不会在运行到上面的地方报错。也没有更详细的提示。。。

你可能感兴趣的:(VS2019,C#,串口Port)