I am writing a WCF service that receives notifications from several modules (DB, other services..) and adds them to a blocking collection, to be processed on a consumer thread that publishes the relevant data to the clients.
A client can request the full data stored on the server, and during this operation i don’t want to accept any new notifications. Basically i want to suspend the blocking collection (or the consumer thread) and resume the notification receiving and processing after completing the client’s request.
What is a good way to implement this behavior?
You can wrap the BlockingCollection and add a Queue for the producer and some sync mechanism internally.
here is a sample:
You can add the BlockingCollection methods you need by just doing them as a wrapper to collection methods.
Here is some output:
This is thread safe…
So you could use X producers and Y consumers if you wish…
If the blocking on ProducerAdd for more producers is a no go then you can use
instead of
and if it fails use
which will be synched back to the collection as soon the locks have been released
Or if you wish just use queu.Enqueue() always for any producer and let the sync thread do its job…