serialport DataReceived事件, 默認是收到一個byte就觸發事件.
lock (thisLock) { int len = sp.BytesToRead; if (len > 0) { Byte[] data = new Byte[len]; try { sp.Read(data, 0, len); } catch (System.Exception) { } SerialPortEventArgs args = new SerialPortEventArgs(); args.receivedBytes = data; Debug.WriteLine("**** port1_DataReceived=" + Encoding.Default.GetString(data)); if (comReceiveDataEvent != null) { comReceiveDataEvent.Invoke(this, args); } } }
舉個例子,實際上返回的數據是*IDN?, 但每次觸發的次數都不一樣
**** port1_DataReceived=* **** port1_DataReceived=IDN? **** port1_DataReceived=* **** port1_DataReceived=I **** port1_DataReceived=DN? **** port1_DataReceived=* **** port1_DataReceived=I **** port1_DataReceived=D **** port1_DataReceived=N? **** port1_DataReceived=* **** port1_DataReceived=I **** port1_DataReceived=D **** port1_DataReceived=N **** port1_DataReceived=? **** port1_DataReceived=* **** port1_DataReceived=IDN **** port1_DataReceived=? **** port1_DataReceived=* **** port1_DataReceived=I **** port1_DataReceived=DN?
DataReceived 事件的處理,本質上是用線程來處理接收數據.
SerialPort類,請勿定義為局部變量, 因為局部變量在函數結束后就釋放了.而線程還沒結束,端口還沒釋放. 就會產生下面2種異常
System.ObjectDisposedException was unhandled Message: An unhandled exception of type 'System.ObjectDisposedException' occurred in mscorlib.dll Additional information: 已關閉 Safe handle
或者
System.UnauthorizedAccessException was unhandled HResult=-2147024891 Message=對端口“COM5”的訪問被拒絕。