开发者

Threading Question [duplicate]

This question already开发者_StackOverflow has answers here: Closed 12 years ago.

Possible Duplicate:

Creating a blocking Queue<T> in .NET?

I have typical producer and consumer threading issue. However the only difference is that the producer is allowed to build up a buffer of 5 items after which it has to wait until some items are consumed.

What would be the best solutions to implement this in c#. Currently I have it implemented using a semaphore however the producer seems to build up a buffer of over 100 items very rapidly. I have no syntax to handle limiting the buffer to 5 items. I was thinking of using a static integer - have the producer increment it - when it reaches 5 the producer goes to sleep. Have the consumer decrement it and wake up the producer.


Why don't you just use a bounded queue (size 5) and have the producer block if the queue is full?


You can use a queue which will ensure first in first out for all your data packets. However since you mentioned that queue gets filled quickly i think you may want to increase the queue limit to some greater number. You mentioned that you would be using sleep to avoid populating more than 5 data in queue, i feel producer is producing at much higher rate than consumer. So you may need to optimize queue size based on requirement.

Also you can have simple event for signalling the consumer thread that queue is filled and needs to be cleared. Semaphores in my view become tedious to handle. Again, this is just a personal opinion.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜