MaYaN
MaYaN

Reputation: 6996

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

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
    });

Upvotes: 3

Views: 656

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063298

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.

Upvotes: 2

Related Questions