c# - 输入缓冲区中的串行输出?

标签 c# .net serial-port

我正在拼凑一个 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。

同样在下面,您可以看到一个终端程序按预期显示来自串行请求的数据。

http://imgur.com/a/bJXeV

enter image description here

最佳答案

先在当前线程读取数据,再调用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/

相关文章:

c# - 如何更改asp面板中分组文本的颜色

python - 用于 python 的 XMODEM

c++ - QT串口读取

c# - 在泛型泛型上指定类型约束

c# - Entity Framework v4 纯代码连接字符串

c# - NancyFX如何处理序列化的DateTime?

c# - F# 是否具有与 C#'s "unsafe"block 等效的语法

.net - 将 SPA 中的 cookie 身份验证升级到 .NET Core 2.0

c# - 提交包含模型集合的表单

python - 如何使用 QSocketNotifier (linux) 监视串行端口?