我想读取我的串行端口,但只有当数据来(我不想轮询)。C#只读串行端口数据来
这就是我的做法。
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);
}
}
我想YOUT读时中断来临。但我该怎么做呢?
此示例代码在.NET 4.5中不再安全。 Console.ReadKey()获取阻止Console.Write()写入任何内容的锁。 Debug.Print()没问题。 – 2013-04-25 13:22:14
我会编辑这个!谢谢! – 2013-04-25 13:23:38
@HansPassant谢谢你。这肯定已经打破了MSDN上的许多线程示例:) – kenny 2013-04-25 13:23:47