c# - 串行数据接收使应用程序卡住

标签 c#

我正在开发一个 Windows 窗体应用程序,我在其中通过按钮发送数据,并不断接收数据以更新一些仪表值。

我面临的问题是,在读取串口时,如果数据来得太快,我的应用程序响应很慢,例如我在读取时可以有 1000Hz 的数据速率。

我附上了我的代码的简化版本。

什么会导致此应用程序挂起?我读到我需要一些单独的线程?但是如何实现呢?

namespace Motor
{
    public partial class Form1 : Form
    {
        SerialPort ComPort = new SerialPort();
        string InputData = String.Empty;
        delegate void SetTextCallback(string text);

        public Form1()
        {
            InitializeComponent();
            ComPort.DataReceived += 
                new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
        }

        private void port_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
        {
            InputData = ComPort.ReadExisting();
            if (InputData != String.Empty)
            {
                this.BeginInvoke(new SetTextCallback(SetText), new object[] { InputData });
            }
        }

        private void SetText(string text)
        {
            if (text.Contains("CM")) 
            {
                // process the text content here
            }
        }
    }
}

最佳答案

这很可能是您的问题

this.BeginInvoke(new SetTextCallback(SetText), new object[] { InputData });

如果您的串行端口出现抖动,则它一直在尝试编码回 UI 线程。您真的需要这么快地更新主 UI 线程吗?你不能每秒或定期做一次

关于声明

What could cause this application to hang? I read that I need some separate thread? But how to achieve this?

SerialPort.DataReceived Event

The DataReceived event is raised on a secondary thread when data is received from the SerialPort object

即它已经在辅助线程上运行,因此启动另一个线程对您没有帮助

更新

引用您的评论

1000hz is the data rate coming from the hardware, its no need for the GUI to be that fast, but i want the gauges to move smooth.

您仍然可以使它们平滑,至少防止 UI 节流是您的关键,请尝试缓冲 200-300 毫秒左右。我只是玩弄它

关于c# - 串行数据接收使应用程序卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48760923/

相关文章:

c# - 防止 Web API 2 输入上的 SQL 注入(inject)

c# - ASP.NET MVC 重定向到 Action 重定向循环

c# - 当鼠标聚焦在面板范围内时添加事件

c# - 数据库到 DropDownList 和 AutoPostBack 到标签

c# - ASP.NET MVC 6 基于 HTTP 状态码处理错误

c# - 是否可以使用 google.protobuf 序列化数据而无需为每个数据字段的长度添加前缀?

c# - 向框中添加换行符

c# - 与 MahAppsMetro ProgressIndicator 绑定(bind)失败

c# - 使用 .NET Core 2.2 发送电子邮件

c# - 当参数实现通用接口(interface)时,NUnit 通用测试夹具不显示