如何使用线程/后台工作者 C# 实现 SerialPort?
我正在编写一个类,它将处理与外部设备的所有串行通信(即读取和写入)。数据以 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的第一个建议是,您应该将其视为网络(套接字)通信。线程问题非常相似。浏览 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.
您只需在另一个线程中实现串行端口的实际使用即可。当需要“通知”您的 UI 时,您可以使用“BeginInvoke”来获取在 UI 线程内运行的实际 UI 处理。
像这样的东西:
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:
只需使用
DataReceived
事件即可。Just use the
DataReceived
event.