Closing a Channel - fthoms/jiminy GitHub Wiki

Closing a Channel

Closing a channel will prevent senders from sending new messages to the channel. Likewise it will also prevent receivers from receiving blocking, unless there are still unconsumed messages in the channel.

var chan = Channel.Make<int>();
chan.Close();
var err = chan.Send(1);
if(err != null) {
	Console.WriteLine(err);
} else {
	Console.WriteLine("this should not be printed");
}

The above code results in the message Channel closed being printed.

Already Sent Messages Are Not Lost When a Channel Closes

Closing a channel after messages have been sent will not result in those messages being lost:

//create a buffered channel
var chan = Channel.Make<int>(2);
chan.Send(1);
chan.Send(2);
chan.Close();

//the channel is now closed so sending additional messages is not possible
var err = chan.Send(3);
if(err != null) {
	Console.WriteLine(err);
} else {
	Console.WriteLine("this should not be printed");
}

//we can still receive the messages sent prior to closing the channel
var (msg, error) = chan.Receive();
if(error != null) {
	Console.WriteLine(error);
}
Console.WriteLine(msg);

(msg, error) = chan.Receive();
if(error != null) {
	Console.WriteLine(error);
}
Console.WriteLine(msg);

//continuing to receive will result in an error
(msg, error) = chan.Receive();
if(error != null) {
	Console.WriteLine(error);
} else {
	Console.WriteLine(msg);
}

This results in the following output:

Channel closed
1
2
Channel closed
Press any key to continue . . .
⚠️ **GitHub.com Fallback** ⚠️