我正在拼凑一个 C# + WPF 应用程序以将串行数据发送到我的数码时钟。
我在使用 C# 应用程序发送和接收数据时性能不佳,而在通过终端程序发送/接收时我没有。
在我的 C# 应用程序中,我的串行输出触发了数据接收处理程序。使用终端程序时我没有收到回声。
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
DateTime aMoment = DateTime.Now;
SerialPort aPort = (SerialPort)sender;
// Because I am updating the UI from a thread other than the main thread.
this.Dispatcher.Invoke((Action)(() =>
{
string indata = aPort.ReadLine();
string outData = aMoment.ToString("yyyy-MM-dd, HH':'mm':'ss.fff, ") + indata + Environment.NewLine;
if (chkEnableDatalog.IsChecked == true)
File.AppendAllText(@txtDatalogPath.Text, outData);
txtSerialIn.Text = indata;
txtDataLogLine.Text = outData;
txtSerialOutHistory.AppendText("<" + indata);
outData = "";
indata = "";
}));
}
有时串行响应的延迟可能会很长 - 很多秒 - 使用终端应用程序,我通常会立即得到响应。
下面是我的 C# 应用程序的屏幕截图。 “<”表示通过数据接收处理程序接收到的数据。其他行是输出。我的时钟对“小时数”的有效响应?是“hours:nn”,其中 nn 是一个整数 1::23。
同样在下面,您可以看到一个终端程序按预期显示来自串行请求的数据。
最佳答案
先在当前线程读取数据,再调用invoke更新UI
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { DateTime aMoment = DateTime.Now;
SerialPort aPort = (SerialPort)sender;
string indata = aPort.ReadLine(); <<<-- Read data before invoke.
// Because I am updating the UI from a thread other than the main thread.
this.Dispatcher.Invoke((Action)((indata ) =>
{
string outData = aMoment.ToString("yyyy-MM-dd, HH':'mm':'ss.fff, ") + indata + Environment.NewLine;
if (chkEnableDatalog.IsChecked == true)
File.AppendAllText(@txtDatalogPath.Text, outData);
txtSerialIn.Text = indata;
txtDataLogLine.Text = outData;
txtSerialOutHistory.AppendText("<" + indata);
outData = "";
indata = "";
}));
关于c# - 输入缓冲区中的串行输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30250688/