Range over Channels - fthoms/jiminy GitHub Wiki

Range over Channels

Having understood what happens when a channel is closed we can move on to iterating over all messages in a channel.

Iterating over a channel is an operation that blocks until there is a message in the channel, or the channel closes.

foreach(var message in chan.Range()) {
	...
}

The above loop terminates when the channel is closed and there are no more messages to consume.

A full example can be seen in the code below:

sealed class ChannelRange : IExample {
    public void Run() {
        var products = Channel.Make<string>();
        Task.Run(() => Producer(products));

        //iterate over all messages in the channel until it closes
        foreach(var msg in products.Range()) {
            Console.WriteLine(msg);
        }
        Console.WriteLine("done");
    }

    void Producer(ISend<string> products) {
        for(var i = 0; i < 10; i++) {
            products.Send($"message {i}");
        }
        products.Close(); //this signals completion to the consumer
    }

This produces the following output:

message 0
message 1
message 2
message 3
message 4
message 5
message 6
message 7
message 8
message 9
done
Press any key to continue . . .
⚠️ **GitHub.com Fallback** ⚠️