考慮下列情形單生產者多消費者的實現
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,然後在沒有更多項目時等待事件 –