C# 串口 已關閉 Safe handle

今天在使用我的通信框架,創建基於串口通信的客戶端時,出現這樣一個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得以解決。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章