I have a situation where I am processing some data in a thread that is fired from an event initially, but it needs to wait until something happens in the main thread before continuing - the issue being there could be any number of these running concurrently. The real basic example:
Event Triggered -> Method set to run in the background on its own thread -> send data using the main thread's send data method -> Wait for an ACK for receipt of that data -> Set the WaitHandle on the main thread -> worker thread will then send the next set of data -> repeat -> exit thread when all data has been sent and ACK'd.
Currently I have one AutoResetEvent that is set each time an ACK comes in - and the worker thread that is running will listen for that - but if there happens to be 10 of those worker threads running at once, and they are all listening to it - it defeats the purpose.
I need to spawn the worker thread, and have it listen (WaitOne) for a specific WaitHandle to be set/reset, and continue based on that only.
What would be the best method for accomplishing something like this? Somehow create an array of WaitHandles and have the worker thread listen for the AutoResetEvent of its index?
I'm not sure on the exact way that your threads and your other process are interacting but a pattern I've used before is a dictionary, where a manual or auto reset event is the value, and you set some kind of ID as the key e.g the event, event sender, user ID whatever.
That way you can search for the relevant ID in the dictionary (using the default indexer) and then wait on the handle. If you need to add wait handles to the list asynchronously (e.g. as the events are raised) you may need to use a
ConcurrentDictionary
class. I'm not exactly sure what you need, but you could also look at a queue if you need to wait on all events being complete before completing some action.Watch out for cross thread synchronisation. You don't want to block your main thread on a GUI app, and you can't edit a GUI from the same thread