private void ReceivedCallBack(IAsyncResult ar) { int errorCode = 0; string errorMsg = "接收成功"; //若SerialPort已经打开 if (ISerialPort != null && ISerialPort.IsOpen) { try { #region 接收数据 int nBytesRec = ISerialPort.BytesToRead; byte[] _dataBuffer = new byte[nBytesRec]; ISerialPort.Read(_dataBuffer, 0, nBytesRec); if (nBytesRec > 0) { errorMsg = string.Format("串口:[{0}]{1}", ISerialPort.PortName, errorMsg); ReceivedData.Clear(); string strtemp = Encoding.Default.GetString(_dataBuffer, 0, nBytesRec); ReceivedData.Append(strtemp); if (ReceivedEvt != null) { System.Windows.Forms.Control target = ReceivedEvt.Target as System.Windows.Forms.Control; if (target != null && target.InvokeRequired) { //非创建控件线程同步调用事件:SerialPortConnected target.Invoke(ReceivedEvt, new object[] { ReceivedData.ToString(), ProCommon.Communal.ToolFunctions.GetSubData(_dataBuffer, 0, nBytesRec) }); } else { //创建控件线程调用事件 ReceivedEvt(Property, ReceivedData.ToString(), ProCommon.Communal.ToolFunctions.GetSubData(_dataBuffer, 0, nBytesRec)); } } } else { errorCode = 1; errorMsg = "接收数据为空"; //Common.SocketClosedEventHandler d=new Common.SocketClosedEventHandler(); if (ClosedEvt != null) { System.Windows.Forms.Control target = ClosedEvt.Target as System.Windows.Forms.Control; if (target != null && target.InvokeRequired) { //非创建控件线程同步调用事件:SocketClosed target.Invoke(ClosedEvt, new object[] { errorCode, errorMsg }); } else { //创建控件线程调用事件 ClosedEvt(Property, errorCode, errorMsg); } } } #endregion } catch { try { if (ClosedEvt != null) { System.Windows.Forms.Control target = ClosedEvt.Target as System.Windows.Forms.Control; if (target != null && target.InvokeRequired) { //非创建控件线程同步调用事件:SocketClosed target.Invoke(ClosedEvt, new object[] { errorCode, errorMsg }); } else { //创建控件线程调用事件 ClosedEvt(Property, errorCode, errorMsg); } } } catch { } } } else { Property.IsConnected = false; //改变连接属性 } }