Middle · Trace · ConcurrentQueue peek does not reserve an item

Explain the two boolean/value pairs when zero is a legitimate queue item.

Think through your answer before opening the explanation.

Runtime & concurrency

using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Reflection;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;

var queue = new ConcurrentQueue<int>();
queue.Enqueue(0);
bool first = queue.TryDequeue(out int value);
bool empty = queue.TryDequeue(out int missing);
Console.WriteLine($"first:{first}:{value}");
Console.WriteLine($"empty:{empty}:{missing}");
Reveal answer and reasoning

The output is first:True:0 followed by empty:False:0. The first TryDequeue successfully removes the real queued zero, so its boolean is true. The queue is then empty, and the second call returns false with the default integer out value zero. Equal out values do not mean the two operations had the same outcome.

A common wrong trace treats zero as an absence sentinel and marks the first call empty, or assumes the second missing value must be a special negative number. This API supplies a separate success result precisely because every integer may be valid data. The snippet creates no concurrent consumers and performs no peek. The desktop fixture separately demonstrates competing observations and distinct removals, while this portable case establishes how callers must pair presence with the returned value before processing or reporting it.

What a strong answer covers

  • A real queued zero is successfully removed.
  • The empty out value is also zero.
  • The success boolean distinguishes presence from absence.

Common pitfall

Discarding the boolean and using a valid data value as an empty sentinel.

Follow-up questions

  1. What changes if two zeros are queued?
  2. What changes if the first item is seven?

Self-review

Choose what to revisit. These marks are your own assessment and are separate from lesson completion.

Primary references

Open lesson and code ↗

← All interview questions