简体   繁体   English

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

[英]How to implement SerialPort with thread/background worker C#?

I'm writing a class which would handle all the serial communications with a external device (ie reading and writing). 我正在编写一个类,该类将处理与外部设备的所有串行通信(即读取和写入)。 The data is being streamed to the computer at 20Hz, and occasionally data is also written to the device. 数据以20Hz的速度流式传输到计算机,偶尔也将数据写入设备。 The class would then output valid data through an event to the main UI. 然后,该类将通过事件将有效数据输出到主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. 我想将此类放在单独的线程中,因为我的先前代码由于在主UI线程中而在设备中引起了一些“卡顿”。

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. 我只是不确定如何使用线程/后台工作者来构造和实现SerialPort类,因为我对此领域没有经验。

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! 任何提示或建议将不胜感激!

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. 通过他们的MSDN文档(如果我没记错的话),可以通过两种不同的方式来做到这一点,即异步和同步。 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. 同样从msdn库的带有线程示例的串行端口到控制台,但是无论如何。

You just implement in another thread the actual use of the SerialPort. 您只需在另一个线程中实现SerialPort的实际使用即可。 When the time comes to "notify" your UI, you use "BeginInvoke" to get the actual UI handling to run inside the UI thread. 当需要“通知”用户界面时,可以使用“ BeginInvoke”来获取实际的用户界面处理,以在用户界面线程中运行。

Something like: 就像是:

string s = _port.ReadLine();

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

只需使用DataReceived事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM