I have a List object in my class and two methods which are used t开发者_运维百科o add and remove items from the list.
There are multiple threads trying to access the list.- I want to ensure that only one thread is updating the list at an instance.
- 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.
- 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?
Maybe you want .NET 4.0's BlockingCollection.
This is a multithreaded producer/consumer pattern. Take a look at this question.
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.
精彩评论