title: Which is the fastest way to tell if a Channel<T> is empty?
body: <p>I am consuming a <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.channels.channel-1" rel="nofollow noreferrer"><code>Channel&lt;object&gt;</code></a> in an <code>await foreach</code> loop, and on each iteration I want to know if the channel is empty. Channels don't have an <code>IsEmpty</code> property, so I am seeing two ways to get this information: the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.channels.channelreader-1.count" rel="nofollow noreferrer"><code>Count</code></a> property and the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.channels.channelreader-1.trypeek" rel="nofollow noreferrer"><code>TryPeek</code></a> method:</p>
  <pre><code>await foreach (var item in channel.Reader.ReadAllAsync())
  {
      ProcessItem(item);
      if (channel.Reader.Count == 0) DoSomething();
  }
  </code></pre>
  <pre><code>await foreach (var item in channel.Reader.ReadAllAsync())
  {
      ProcessItem(item);
      if (!channel.Reader.TryPeek(out _)) DoSomething();
  }
  </code></pre>
  <p><strong>My question is:</strong> Which is the most performant way to get the <code>IsEmpty</code> information? Is it one of the above, or is it something else?</p>
  <p>I should mention that my channel is unbounded, but I am open to switching to a bounded channel (<a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.channels.channel.createbounded" rel="nofollow noreferrer"><code>Channel.CreateBounded&lt;object&gt;(Int32.MaxValue)</code></a>) in case this would be beneficial performance-wise.</p>
  <p>My unbounded channel is configured with the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.channels.channeloptions.singlereader" rel="nofollow noreferrer"><code>SingleReader</code></a> option equal to <code>false</code> (the default value).</p>
  <p>Another detail that might be important: most of the time the check for emptiness will be negative. The producer of the channel tends to write hundreds of items in frequent bursts. The <code>DoSomething</code> method triggers such a burst.</p>