views:

61

answers:

3

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!

A: 

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;
});
S.C. Madsen
A: 

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.

Markus Andersson
I did some further investigations on the msdn site, and I read that the DataReceieved event is created on a separate thread. So does this mean that what ever is handled inside that event handler is already on a separate thread? Is then what I'm trying to do redundant?
yeastbeast
Well yes i guess it is... =) Just make sure that for the UI you use BackgroundWorker or something similar so you don't "hang" the UI, that is where you need to use threading. So the whole handling of the serial port is in one thread, within that you use the event.
Markus Andersson
A: 

Just use the DataReceived event.

leppie