C# 串口 已关闭 Safe handle

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yeqi3000/article/details/41983517

今天在使用我的通信框架,创建基于串口通信的客户端时,出现这样一个BUG:

未处理 System.ObjectDisposedException
  Message=已关闭 Safe handle
  Source=mscorlib
  ObjectName=""
  StackTrace:
       在 System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
       在 System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
       在 Microsoft.Win32.UnsafeNativeMethods.GetOverlappedResult(SafeFileHandle hFile, NativeOverlapped* lpOverlapped, Int32& lpNumberOfBytesTransferred, Boolean bWait)
       在 System.IO.Ports.SerialStream.EventLoopRunner.WaitForCommEvent()
       在 System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       在 System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

当这个BUG出现时,程序直接崩溃,无法跟踪到错误代码位置。

经过一番测试,查找问题。发现在一个函数内利用SerialPort创建了串口通信实例后,没有将该实例放入任何其他容器中进行缓存,从而导致了上述崩溃BUG的产生。

后来修改代码,将该实例放入了一个全局变量List<通信客户端>集合中,该BUG得以解决。

猜你喜欢

转载自blog.csdn.net/yeqi3000/article/details/41983517