سؤال

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

نصائح أخرى

I think you're digging a little too low-level in your abstractions. Is there a reason you can't use a much more typical producer-consumer model with a queue or two to handle in-flight requests and responses? It's going to be a lot easier to get it correct when you're not trying to recreate low-level synchronization primitives.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top