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”的访问被拒绝。