InfoLearner
InfoLearner

Reputation: 15598

How to block and inform threads

I have a List object in my class and two methods which are used to add and remove items from the list.
There are multiple threads trying to access the list.

  1. I want to ensure that only one thread is updating the list at an instance.
  2. If a list is empty and a thread wants to remove an item then I want to make the thread wait till there is an item in the list.
  3. When an item is inserted in the list then I want to inform other threads which are waiting to access the list that the list is not empty anymore and they can remove the items (using events).

What is the best mechanism to achieve this goal?

Upvotes: 2

Views: 198

Answers (3)

dexter
dexter

Reputation: 7203

ReaderWriterLock object will be a good fit - allows for parallel reads but will block all the other threads while one thread is writing to the collection.

Upvotes: 1

Nicolas Repiquet
Nicolas Repiquet

Reputation: 9265

This is a multithreaded producer/consumer pattern. Take a look at this question.

Upvotes: 2

Brian
Brian

Reputation: 118865

Maybe you want .NET 4.0's BlockingCollection.

Upvotes: 5

Related Questions