Range Over Channels in C#

Our example demonstrates how to iterate over values received from a channel. In C#, we’ll use a BlockingCollection<T> to simulate a similar behavior.

using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        // We'll iterate over 2 values in the queue.
        var queue = new BlockingCollection<string>(boundedCapacity: 2);
        queue.Add("one");
        queue.Add("two");
        queue.CompleteAdding();

        // This foreach loop iterates over each element as it's
        // received from queue. Because we called CompleteAdding()
        // on the queue above, the iteration terminates after
        // receiving the 2 elements.
        foreach (var elem in queue.GetConsumingEnumerable())
        {
            Console.WriteLine(elem);
        }
    }
}

When you run this program, you’ll see:

one
two

This example also shows that it’s possible to complete adding to a non-empty collection but still have the remaining values be received.

In C#, we use a BlockingCollection<T> to simulate a channel-like behavior. The BlockingCollection<T> class provides blocking and bounding capabilities, which are similar to Go’s buffered channels.

Here’s a breakdown of the C# code:

  1. We create a BlockingCollection<string> with a capacity of 2, similar to the buffered channel in the original example.

  2. We add two items to the collection using the Add method.

  3. We call CompleteAdding() to signal that no more items will be added to the collection. This is similar to closing a channel in Go.

  4. We use a foreach loop with GetConsumingEnumerable() to iterate over the items in the collection. This method will block if the collection is empty and will stop when the collection is empty and CompleteAdding() has been called.

  5. Inside the loop, we print each element, just like in the original example.

This C# code provides similar functionality to the Go example, demonstrating how to iterate over a collection that behaves like a channel.