DEV Community

Discussion on: Read-once variable - R1V, ROV, ... - in C#

Collapse
 
thebuzzsaw profile image
Kelly Brown • Edited

I use System.Threading.Channels for this. Read this if you want a super detailed introduction to channels in general. For your specific problem, I simply make a bounded channel with a capacity of 1.

var channel = Channel.CreateBounded<int>(1);

I love that the designers made the decision to have a separate ChannelReader<T> and ChannelWriter<T>. You can simply pass channel.Reader to your consumer and channel.Writer to your producer (if you desire that separation). This will give you what you want. You can call channel.Reader.TryRead. If it succeeds, it will be removed from the channel. Otherwise, it just informs you there was no value to take.

if (channel.Reader.TryRead(out var value))
{
    // Use the value.
}

Channels can be further customized by way of BoundedChannelOptions. For instance, you can specify BoundedChannelFullMode, which determines the desired outcome if you attempt to write to the channel when it's already full.

Collapse
 
bugmagnet profile image
Bruce Axtens

I am receiving that as a late Christmas present. Thank you very much.