I am asking this in the WPF forum because this is a WPF app but this question does not necessarily pertain to WPF, i.e. the UI thread.
Here is the scenario:
I have three (3) threads. Thread One (1) call it the Master Thread; Thread Two (2) is a Ethernet Comm thread; and Thread Three (3) is a GPIB comm thread. Both communication threads handle asynchronous communications from remote entities. At this time there is only one entity hanging off each comm type.
I have implemented a mix of EventWaitHandles and delegates. This all works pretty well. Just think this architecture is a bit ...... ugly. So which one is better/safer?
My concern is as follows. With delegates, for example, the Master thread registers an event handler with Thread 2 and an event handler with Thread 3 for messages that come in. Obviously data could come in near simultaneously. So Thread 2 encases a message in an EventArg and invokes the event on the Master thread. The Master Thread begins processing and then Thread 3 encases its message in an EventArg and invokes the event on the Master Thread. What happens? Does the Master Thread stop in the middle of handling the first event to service the second one? Does the second event wait until the first event is processed? What if Thread 2 gets another message and invokes the event again while the Master is processing the first event?
I wonder if using a queue and an manual Reset EventWaitHandle is not a better idea as the Thread 2 can check the status and wait until it is reset before putting the message in the queue and setting the EventWaitHandle again.
What version of Visual Studio are you using? Use the new async keyword. If you are using VS2010, you need to install the Async CTP. The async keyword produces *MUCH* cleaner code since all the syncronization / threading is hidden from the developer.