我希望能够在串口接收到数据的时候读取数据,而非轮询方式。
以下是我的实现方式:
Schnittstelle = new SerialPort("COM3");
Schnittstelle.BaudRate = 115200;
Schnittstelle.DataBits = 8;
Schnittstelle.StopBits = StopBits.Two;
....
然后我启动了一个线程
beginn = new Thread(readCom);
beginn.Start();
在我的readCom函数中,我正在连续读取数据(有点像轮询 :()
private void readCom()
{
try
{
while (Schnittstelle.IsOpen)
{
Dispatcher.BeginInvoke(new Action(() =>
{
ComWindow.txtbCom.Text = ComWindow.txtbCom.Text + Environment.NewLine + Schnittstelle.ReadExisting();
ComWindow.txtbCom.ScrollToEnd();
}));
beginn.Join(10);
}
}
catch (ThreadAbortException)
{
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
当中断到来时,我希望您可以读取它。但是我该如何做到这一点?