public void MonitorAndLogTrades() { while (true) { Trade nextTrade; bool done = _queue.TryDequeue(out nextTrade); if (done) { _staffLogs.ProcessTrade(nextTrade); Console.WriteLine("Processing Transaction from " + nextTrade.Person.Name); } else if (_workingDayComplete) { //When trading day is complete no more transactions will be done so no logs are expected Console.WriteLine("No more sales to log - exiting"); return; } else { //There are no items in the queue, but the working day is not over yet. So the thread will sleep for some time and the check the queue again Console.WriteLine("No transactions available"); Thread.Sleep(500); } } }
public void MonitorAndLogTrades() { while (true) { try { //If there is no item available in the queue the Take method will simply wait until an items become available. //Now if the queue is empty and there are no more items to be expected to be in the queue, but still we try a Take() operation, then Take() will throw an error. So we need to explicitly tell the BlockingCollection that no more items are expected further. //In CompleteAdding() method we make that explicit call to tell the BlockingQueue that no more items are expected var nextTransaction = _queue.Take(); _staffLogs.ProcessTrade(nextTransaction); Console.WriteLine("Processing Transaction from " + nextTransaction.Person.Name); } catch (InvalidOperationException ex) { Console.WriteLine(ex.Message); return; } } }