考虑下列情形单生产者多消费者的实现
private BlockingCollection<Consumer> consumers { get; set; }
ThreadPool.QueueUserWorkItem((x) => {
while (consumers.Count == 0)
Thread.Sleep(20);
Consumer consumer;
if (consumers.TryTake(out consumer)) {
var result = consumer.Read(data);
//do stuff with result
if (consumers.TryAdd(consumer)) {
//ok
}
}
});
是否有办法避免这种超时的时候没有提供一个消费者来处理请求?
如果你使用'主题睡觉,你做错了什么。为什么不使用'WaitHandle'来代替线程呢? – Dai
你有没有试过'System.Collections.Concurrent.BlockingCollection'为前。它有一个有限的能力。 – Eser
'消费者'的类型是什么?你需要考虑使用[semaphore](https://msdn.microsoft.com/en-us/library/system.threading.semaphore%28v=vs.110%29.aspx)来允许消费者获取X项目max,然后在没有更多项目时等待事件 –