今天在使用我的通信框架,创建基于串口通信的客户端时,出现这样一个BUG:
- 未处理System.ObjectDisposedException
- Message=已关闭Safehandle
- Source=mscorlib
- ObjectName=""
- StackTrace:
- 在System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean&success)
- 在System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandlepHandle,Boolean&success)
- 在Microsoft.Win32.UnsafeNativeMethods.GetOverlappedResult(SafeFileHandlehFile,NativeOverlapped*lpOverlapped,Int32&lpNumberOfBytesTransferred,BooleanbWait)
- 在System.IO.Ports.SerialStream.EventLoopRunner.WaitForCommEvent()
- 在System.Threading.ThreadHelper.ThreadStart_Context(Objectstate)
- 在System.Threading.ExecutionContext.Run(ExecutionContextexecutionContext,ContextCallbackcallback,Objectstate,BooleanignoreSyncCtx)
- 在System.Threading.ExecutionContext.Run(ExecutionContextexecutionContext,ContextCallbackcallback,Objectstate)
- 在System.Threading.ThreadHelper.ThreadStart()
- InnerException:
当这个BUG出现时,程序直接崩溃,无法跟踪到错误代码位置。
经过一番测试,查找问题。发现在一个函数内利用SerialPort创建了串口通信实例后,没有将该实例放入任何其他容器中进行缓存,从而导致了上述崩溃BUG的产生。
后来修改代码,将该实例放入了一个全局变量List<通信客户端>集合中,该BUG得以解决。
原文地址:https://blog.csdn.net/yeqi3000/article/details/41983517