Trouble with Multi Threading

  • Thread starter Thread starter jayderk
  • Start date Start date
J

jayderk

Hello All,

I am in the middle of creating a class that I want to use with Serial IO per
the MVP on this forum.

I am still having trouble with my design process I think.

I created a class that is designed to basically receive messages from the
port. It is a CommEvent
private void port_DataReceived()
{
byte[] data = port.Input;
RxMESSAGE += Encoding.ASCII.GetString(data,0,data.Length);
}

this class is created from a WinCE form.

there suggestion was to create a seperate thread that receives data.
my question(s) in this process is

1)if I have a class that is created from a WinCE form( myThread = new
Utility.myThreadClass(); ) with the event port_DataReceived. Will that event
raise without locking up my WinCE form?

2) how do I start a thread that will allow this event to be raise and allow
me to continue working on my WinCE form? In every other situation I have
written a thread that calls one function, once that function was done the
thread was done also, in this case I am trying to start a thread the allows
an event to fire?
 
I would simply have my event handler with your form, then once the event
handler is created, create and start a new thread to perform the work you
need to, freeing up the main thread should the work be substantial.
 
Inline....
1)if I have a class that is created from a WinCE form( myThread = new
Utility.myThreadClass(); ) with the event port_DataReceived. Will that
event
raise without locking up my WinCE form?

Yes. The DataReceived event comes in on a separate thread context - the one
that the serial class is using for listening to the serial line. To affect
the UI from the DataReceived evednt handler, you *must* use Invoke.
2) how do I start a thread that will allow this event to be raise and
allow
me to continue working on my WinCE form? In every other situation I have
written a thread that calls one function, once that function was done the
thread was done also, in this case I am trying to start a thread the
allows
an event to fire?

I'd do a couple things.

1. In the event handler, simply append data to a global queue then raise
another event to your app
2. Create a thread that listens for the new event raised in #1, and from
that handler, read from the gloabl queue and do something with it - remember
to use Invoke if you affect the UI.

This will prevent blocking the receiving thread and give the best possible
serial throughput, plus it allows you to monitor and handle incoming data
without blocking the UI.

Sure, it's a bit more complex than linear procedural code, but it's the
right way to make the app robust and responsive.
 
Back
Top