【发布时间】:2018-08-04 10:59:03
【问题描述】:
我正在尝试构建一个 WPF 应用程序,该应用程序可以从串行端口读取数据并且不会阻塞 UI 线程,但我对应该如何做有点卡住了。
我的 *.xaml.cs 文件中的代码如下
private void testConnection_Click(object sender, RoutedEventArgs e)
{
string correctPort = "COM6";
SerialPortConnection serialPortTestConnection = new SerialPortConnection(correctPort);
}
在我的 SerialPortCommunications 中,我得到了这样的结果:
public SerialPortCommunications(string comPort)
{
SerialPort mySerialPort = new SerialPort(comPort);
mySerialPort.BaudRate = 2400;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 7;
mySerialPort.Handshake = Handshake.None;
mySerialPort.Encoding = ASCIIEncoding.ASCII;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
mySerialPort.WriteLine("C");
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
String s = sp.ReadExisting();
if (s == "\r")
{
Console.WriteLine(tempReadingString);
tempReadingString = string.Empty;
} else
{
tempReadingString += s;
}
}
我确实收到了设备的第一个响应,但是即使端口保持打开状态,它也会在此之后停止。我确信传递值“C”会不断返回值(使用超级终端测试)。
不胜感激。
【问题讨论】:
标签: c# wpf asynchronous serial-port