如何使用线程/后台工作者 C# 实现 SerialPort?

发布于 2024-09-12 18:38:56 字数 285 浏览 3 评论 0原文

我正在编写一个类,它将处理与外部设备的所有串行通信(即读取和写入)。数据以 20Hz 的频率传输到计算机,有时数据也会写入设备。然后,该类将通过事件将有效数据输出到主 UI。 我想将这个类放在一个单独的线程中,因为我之前的代码在设备中导致了一些“口吃”,因为它位于主 UI 线程中。

我只是不确定如何使用线程/后台工作人员构建和实现 SerialPort 类,因为我在这方面缺乏经验。

线程/后台工作人员中是否只有数据接收事件存在? 如何将数据传入和传出创建的线程/后台工作线程?

任何提示或建议将不胜感激!

I'm writing a class which would handle all the serial communications with a external device (i.e. reading and writing). The data is being streamed to the computer at 20Hz, and occasionally data is also written to the device. The class would then output valid data through an event to the main UI.
I want to put this class in a separate thread because my previous code caused some 'stuttering' in the device since it was in the main UI thread.

I'm just unsure of how to structure and implement the SerialPort class with a thread/background worker because I'm inexperienced in this area.

Would only the data received event exist inside the thread/background worker?
How would you pass data in and out of the created thread/background worker?

Any hints or suggestions would be much appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蓝天白云 2024-09-19 18:38:56

我的第一个建议是,您应该将其视为网络(套接字)通信。线程问题非常相似。浏览 MSDN 文档,他们有(如果我没记错的话)两种不同的方法来执行此操作:异步和同步。我个人会使用其中一种异步方式。

您还可以查看新的任务库。

开始查看该内容,如果有其他问题请回来 =)

也来自带有线程的 msdn 库串行端口 示例 这是控制台,但无论如何。

My first tip is that you should think of it like it was network (Socket) communication. The threading issues are much the same. Looking thru the MSDN documentation they have (if I remember correctly) two different ways of doing this, async and sync. I personally would use one of the async ways.

You can also take a look at the new Task library.

Start looking in to that and come back if you have further questions =)

Also from the msdn library serial port with threading example this is to console, but anyway.

像你 2024-09-19 18:38:56

您只需在另一个线程中实现串行端口的实际使用即可。当需要“通知”您的 UI 时,您可以使用“BeginInvoke”来获取在 UI 线程内运行的实际 UI 处理。

像这样的东西:

string s = _port.ReadLine();

form.BeginInvoke((MethodInvoker)delegate
{
  _textbox.Text = s;
});

You just implement in another thread the actual use of the SerialPort. When the time comes to "notify" your UI, you use "BeginInvoke" to get the actual UI handling to run inside the UI thread.

Something like:

string s = _port.ReadLine();

form.BeginInvoke((MethodInvoker)delegate
{
  _textbox.Text = s;
});
紧拥背影 2024-09-19 18:38:56

只需使用 DataReceived 事件即可。

Just use the DataReceived event.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文