Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is incrementing an Integer inside IAsyncEnumerable thread-safe in C#?

Tags:

c#

.net

I am using the latest IAsyncEnumerable feature in C# and have the following code:

private async Task KeepStreaming()
{
    int someCounter = 0;
    
    await foreach(var item in _someService.ReadAllAsync())
    {
        someCounter++;
        // skipped rest of the logic for brevity
    }
}

Do I have to worry about thread-safety when incrementing the counter?

How about if _someService.ReadAllAsync() was replaced with _someChannel.Reader.ReadAllAsync() assuming the channel was created as following:

Channel<Foo> _someChannel = Channel.CreateUnbounded<Foo>(
    new UnboundedChannelOptions {
        AllowSynchronousContinuations = false,
        SingleReader = true,
        SingleWriter = false
    });
like image 730
MaYaN Avatar asked May 20 '26 18:05

MaYaN


1 Answers

Yes it is safe, and no you don't need to worry about it.

That is entirely thread-safe as long as the code consuming the iterator doesn't break any usage expectations by accessing the iterator concurrently (which would need to be written explicitly - meaning "not await foreach" - and would be a fault of the consuming code, not yours).

To be explicit (see comments) - it is relevant here that the variable in discussion is scoped within the iterator block. If it were a field on the instance, then it could have thread safety concerns.

like image 72
Marc Gravell Avatar answered May 22 '26 08:05

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!