C# 智能设备串口应用开发中遇到的关于DataReceived事件委托的问题,请帮忙分析一下原因
我使用VS2005 开发基于wince 5.0的串口应用程序,在打开串口时使用如下设置: m_serialPort.ReadBufferSize = 1024;
m_serialPort.PortName = "COM3";
m_serialPort.BaudRate = 57600;
m_serialPort.Parity =
m_serialPort.DataBits = 8;
m_serialPort.StopBits =
m_serialPort.ReadTimeout = 10;
m_serialPort.ReceivedBytesThreshold = 1; //事件触发频率,每收到1个字节长度数据即出发接收事件
m_serialPort.DataReceived += new SerialDataReceivedEventHandler(m_serialPort_DataReceived); //绑定接收事件函数
如果从其他设备向此终端模拟发送数据,没隔1秒发送一次,终端每隔5、6秒才收到一串数据。
但是,经过反复尝试,将串口设置改成(多重复几次设定事件处理函数委托):
m_serialPort.ReadBufferSize = 1024;
m_serialPort.PortName = "COM3";
m_serialPort.BaudRate = 57600;
m_serialPort.Parity =
m_serialPort.DataBits = 8;
m_serialPort.StopBits =
m_serialPort.ReadTimeout = 10;
m_serialPort.ReceivedBytesThreshold = 1; //事件触发频率,每收到1个字节长度数据即出发接收事件
m_serialPort.DataReceived += new SerialDataReceivedEventHandler(m_serialPort_DataReceived); //绑定接收事件函数
m_serialPort.DataReceived += new SerialDataReceivedEventHandler(m_serialPort_DataReceived); //绑定接收事件函数
m_serialPort.DataReceived += new SerialDataReceivedEventHandler(m_serialPort_DataReceived); //绑定接收事件函数
m_serialPort.DataReceived += new SerialDataReceivedEventHandler(m_serialPort_DataReceived); //绑定接收事件函数
事件处理函数如下:
public void m_serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (m_serialPort.Read(readBuff, m_nReadBytes, 1) == 1)
{
if (readBuff[m_nReadBytes] == 0x02)
{
m_nReadBytes = 0;
}
m_nReadBytes++;
if (readBuff[m_nReadBytes - 1] == 0x03)
{
Marshal.Copy(readBuff, 0, hglobal, m_nReadBytes); // System.Runtime.InteropServices.把你的数据从byte[]复制到这段内存空间
Message msg = Message.Create(m_msgWnd.Hwnd, MsgWindow.WM_RECVDATA, hglobal, (IntPtr)m_nReadBytes);
MessageWindow.PostMessage (ref msg);
m_nReadBytes = 0;
}
}
}
catch (Exception ee)
{
//如果读取超时,可能会出发此异常
}
}
串口接收就正常了。小弟刚开始接触C#,请高手指点一下,这是什么原因?
[ 本帖最后由 wzg_soullon 于 2010-1-9 12:46 编辑 ]