开发者

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

I'm writing a class which would handle all the serial communications with开发者_Go百科 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!


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


Just use the DataReceived event.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜