gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:45:30 26 4
gpt4 key购买 nike

我正在开发一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com