当事件第一次触发时,如何执行一次方法



我有以下事件:

private void button1_Click(object sender, EventArgs e)
{
try
{
sPort = new SerialPort();
sPort.PortName = comboBox1.Text;
sPort.BaudRate = Convert.ToInt32(comboBox5.Text);
sPort.DataBits = Convert.ToInt32(comboBox3.Text);
sPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox2.Text);
sPort.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox4.Text);
sPort.Handshake = Handshake.None;
sPort.RtsEnable = true;
sPort.DtrEnable = true;
sPort.DataReceived += new SerialDataReceivedEventHandler(sPort_datareceived);
sPort.Open();
}
catch (Exception err)
{
MessageBox.Show(err.Message, MessageBoxButtons.OK.ToString());
}
}
private void sPort_datareceived(object sender, SerialDataReceivedEventArgs e)
{                
SerialPort sp = (SerialPort)sender;
datain = sp.ReadExisting();                
this.Invoke(new EventHandler(idextraction));
}
public string namingid;
private void idextraction(object sender, EventArgs e)
{
Match matchid = Regex.Match(datain, @"bd{12}b");
namingid = matchid.Value;
namingid = namingid.Substring(namingid.Length - 7);
this.Invoke(new EventHandler(writesyncdata));
}
private void writesyncdata(object sender, EventArgs e)
{
try
{
TextWriter tw = new StreamWriter(@"C:\intdata\" + namingid + ".txt");
tw.Write(datain);
tw.Close();
}
catch (Exception err)
{
MessageBox.Show(err.Message, MessageBoxButtons.OK.ToString());
}
}

假设此事件触发了X次,然后停止,然后再次触发,循环继续。当事件触发X次时,时间间隔在1-2秒之间。我想在事件第一次触发时调用我的方法一次,然后停止,但我的方法应该在每次循环开始时执行一次。

当idextraction((调用时,它不起作用,因为缓冲区中的数据处理较少(填充完整数据需要1-2秒,但我的方法在此之前调用,这就是问题所在(

我知道如何执行一个方法一次,但由于事件在短时间内触发了很多次,所以我的方法也不想这样。有人知道怎么做吗?

每次事件触发时,您都不知道有多少信息可用。你有责任在收到所有数据时对其进行缓冲,直到你有有用的事情处理为止。有多种方法可以做到这一点,比如你可以有一个字节队列。当收到数据时,您将数据添加到队列的末尾,并检查数据是否足以处理它。如果足够,则调用您的处理例程。如果不是,请等待接收到更多数据。对于您打开的每个串行端口,都需要一个单独的队列。

最新更新