简体   繁体   中英

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. 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!

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.

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;
});

只需使用DataReceived事件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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