sonar-dotnet icon indicating copy to clipboard operation
sonar-dotnet copied to clipboard

New Rule: Async methods using yield should have a decorated cancellation token

Open Corniel opened this issue 3 years ago • 0 comments

As proposed by the community: [https://community.sonarsource.com/t/c-find-missing-enumeratorcancellation-parameter/58675](Aysnc methods using yield should have a decorated cancellation token).

Descrption

CancellationToken parameters with the [EnumeratorCancellation] attribute are needed on methods, returning IAsyncEnumerable and use yield return in their method body. Otherwise it is not possible to cancel that enumerable even if the IAsyncEnumerator was disposed. Therefore a missing [EnumeratorCancellation] parameter on such a method is very likely a bug, because the enumerable continues although the enumerator was already disposed.

Noncompliant Code Example

using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;

public async IAsyncEnumerable<int> Numbers(CancellationToken token)
{
    yield return 13;
}

Compliant Solution

using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;

public async IAsyncEnumerable<int> Numbers([EnumeratorCancellation] CancellationToken token)
{
    yield return 13;
}

Corniel avatar Aug 16 '22 11:08 Corniel