How to pass data from a form to a thread [C#/CS 2005]

Shaitan00

Junior Contributor
Joined
Aug 11, 2003
Messages
358
Location
Hell
Application - CLIENT / SERVER program (currently working on the CLIENT-side)
Background information - On my CLIENT I have a main form (fBoard) that creates & starts a sender thread (thTcpSender) that is responsible for sending data/information (such as a key-strokes, extendable to any kind of object) to the SERVER. So, when the user (on the CLIENT fBoard) hits the UP-Key I need to send the key-stroke information to the SERVER...

Now, this is where the fun comes in... I need fBoard to somehow provide the sender-thread (thTcpSender) with the information (in this case the key-stroke "UP" which is a string) and then tell it to send the information to the server....
Problem is - I have no clue how I can perform both of those actions...
1- Provide the data (key stroke as a string, in this case "UP") to the thread (thTcpSender)
2- Notify the thread (thTcpSender) that I (fBoard) have provided it with data that needs to be sent so that it will actually perform the required actions...

So... I have a "theoretical idea" that could or could-not work...
- Use a queue that I could share between fBoard and thTcpSender (thread safe using ReaderWriterLock), in the queue I would place a DataSet with two columns [Type, Data] and send the DataSet across the network to the SERVER, so for this example my DataSet would be ["Movement", "UP"], or also ["Data", byte[]], etc...
Still not sure how I could notify the sender that data is ready, maybe have it check to see if the repository (queue?) is empty using (using a while loop) and when something appears have it send the data? Doesn't sound very efficient... There has to be a more conventional and efficient way to handle this situation...

Any ideas, hints, and help would be greatly appreciated, thanks
 
AutoResetEvent

If only two threads are going to access the queue, using a ReaderWriterLock is unnecessary. Both C# and VB.Net have simple synchronization constructs in the form of the lock and SyncLock statements.

As for notifying the other thread that data is available, the System.Threading namespace contains various wait objects. I would recommend looking at the AutoResetEvent object, as it allows one thread to send a simple signal to other threads waiting on it:

  1. AutoResetEvent object created
  2. thTcpSender calls WaitOne on the event, causing it to block
  3. fBoard adds data to the queue (using lock to make threadsafe)
  4. fBoard calls Set on the event, causing thTcpSender to unblock
  5. thTcpSender reads from the queue (using lock)
  6. Go to 2

Good luck :cool:
 
Back
Top