开发者

How to block and inform threads

开发者 https://www.devze.com 2023-01-27 11:30 出处:网络
I have a List object in my class and two methods which are used t开发者_运维百科o add and remove items from the list.

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.

  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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消